我有一个登录组件。
加载时,它会从本地存储中获取用户名。
如果存在,我希望将焦点设置在密码字段上。
目前,我正在商店订阅中这样做。
@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/