【发布时间】:2020-03-27 08:06:00
【问题描述】:
我正在尝试编写一个使用 ngrx 存储的自定义结构指令。在商店里,我有一面旗帜,告诉我是否应该展示一些组件。我想让我的自定义指令订阅该商店,并根据该标志是否为真或该标志是否为假但组件具有应呈现的数据来呈现组件。代码如下:
@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 上的更改,除非showEmpty 为真。
【问题讨论】:
标签: angular observable ngrx subscription