我正在尝试编写一个使用 ngrx 存储的自定义结构指令。在商店内部,我有一个标志,告诉我是否应该展示一些组件。我想让我的自定义指令订阅该存储,并根据该标志是否为 true 或该标志是否为 false 但组件具有应渲染的数据来渲染组件。代码如下:
@Directive({ selector: '[showIfExists]' })
export class ShowIfExistsDirective {
showEmpty$ = this.store.select(getShowHideState).subscribe((value) => {
this.showEmpty = value;
});
showEmpty: boolean;
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private store: Store<AppState>) {
}
ngOnDestroy() {
this.showEmpty$.unsubscribe();
}
@Input() set showIfExists(condition: boolean) {
if (this.showEmpty || (!this.showEmpty && condition)) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
我最终看到的是订阅正确更新了我的 showEmpty
属性,但是 set showIfExists
没有响应 showEmpty
上的更改code>,除非 showEmpty
为 true。
最佳答案
您需要在订阅中创建或清除 View 。我建议您从输入创建另一个 Observable (BehaviorSubject)。
@Directive({ selector: '[showIfExists]' })
export class ShowIfExistsDirective {
showEmpty$: Observable<boolean> = this.store.select(getShowHideState);
showIfExists$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private store: Store<AppState>) {
combineLatest([this.showEmpty$, this.showIfExists$]).pipe(
distinctUntilChanged(),
map(([showEmpty, showIfExists]) => showEmpty || condition), // !showEmpty is btw redundant
// don't forget to unsubscribe your way
).subscribe(activate => {
if (activate) this.viewContainer.createEmbeddedView(this.templateRef)
else this.viewContainer.clear();
});
}
@Input() set showIfExists(condition: boolean) {
this.showIfExists$.next(condition);
}
}
关于angular - 在自定义结构指令 Angular 6+ 中使用 NGRX Observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59143520/