首页 > 解决方案 > NGRX 通过@Effect 将重点放在输入上

问题描述

我有一个登录组件。

当它加载时,它会从本地存储中获取用户名。

如果存在,我希望将焦点设置在密码字段上。

目前,我正在商店订阅中进行。

@ViewChild('passfield', { static: false }) passfield: ElementRef;

// ...

this.store.select('login')
  .subscribe(state => {
    this.model.user = state.username;
    if (this.model.user) {
      // focus on pass field if user is not empty
      setTimeout(() => this.passfield.nativeElement.focus(), 0); // <---
    }
  });

我想将焦点转移到我的组件中的效果和清晰的逻辑上。

标签: angularngrxngrx-effects

解决方案


我会稍微重写一些东西,但绝对要保留组件中的逻辑:

private destroy$ = new Subject<boolean>();

this.store.select('login').pipe(
  takeUntil(this.destroy$),
  filter(user => user.username),
  tap(() => this.passfield.nativeElement.focus())
).subscribe();

ngOnDestroy() {
  this.destroy$.next(true);
}

我不认为使用副作用从组件检查商店中的某些内容然后使用同一组件的 DOM 是明智的。可能,但不必要地复杂。

编辑:NGRX 用于状态管理,组件作为状态的纯粹反映。组件应该是选择它如何解释给定状态的组件。


推荐阅读