angular - NGRX 通过@Effect 将焦点放在输入上

标签 angular ngrx ngrx-effects

我有一个登录组件。

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

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

目前,我正在商店订阅中这样做。

@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); // <---
    }
  });

我想将重点转移到效果上,并从我的组件中清除逻辑。

  • 可以吗?
  • 我们可以使用 view child in effect 吗?
  • 我们想做吗?有更好的方法吗?

最佳答案

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

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,组件作为状态的纯粹反射(reflect)。该组件应该是选择它如何解释给定状态的组件。

关于angular - NGRX 通过@Effect 将焦点放在输入上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57264962/

相关文章:

javascript - CKeditor5 + Angular : how to display video added via editor

node.js - 错误: Cannot find module 'shrink-ray'

javascript - 绘制自定义形状和弯曲矩形

javascript - Angular ngrx : TypeError: Cannot freeze array buffer views with elements

angular - 添加StoreModule.forFeature(...)后无法访问存储的数据

angular - NGRX 从有效的参数化选择器获取状态

html - Angular Material 选项卡未突出显示

angular - 检查 ngrx 中可能要加载的列表中是否存在元素

Angular 10 | ngrx 效果 |单元测试 |不能将类作为函数调用

angular - 使用 Marbles 对外部 URL 进行单元测试 NGRX 效果