Ist*_*ván 6 eventemitter typescript angular
我有QueryList一个组件.我正在动态添加其他组件,这些组件将存在于其中QueryList,但如果我订阅了它changes,则QueryList没有任何反应.我以为是因为我订阅了ngAfterViewInit,但QueryList现在undefined还没有ngOnInit.在这里,我有plunkr.
码:
@Component({
...
})
export class AppComponent {
@ViewChildren(ControlFactoryDirective) factories:
QueryList<ControlFactoryDirective>
ngAfterViewInit() {
this.factories.changes.subscribe(() => {
console.log('changed')
})
}
}
Run Code Online (Sandbox Code Playgroud)
小智 11
问题是,到达您的factories财产的列表已经预先填充.因此,您只是在第一次填充之前没有机会订阅它的更改.但是,当然,以后发生的所有更改都会传递给您的订阅者.
以下是更新示例的plunkr - 请注意工厂现在有一个setter,它证明它是预填充的(你通常不需要它在一个真正的应用程序中,那只是为了找出框架中的值)
我认为这是一种完全有效的行为.因此ngAfterViewInit,在QueryList中循环遍历值,并在订阅者中执行相同的操作:
ngAfterViewInit() {
this.processChildren(); // first call to processChildren
this.factories.changes.subscribe(_ =>
this.processChildren() // subsequent calls to processChildren
);
}
private processChildren(): void {
console.log('Processing children. Their count:', this.factories.toArray().length)
}
Run Code Online (Sandbox Code Playgroud)
您还可以startWith(undefined)像这样添加:
ngAfterViewInit() {
this.factories.changes.pipe(startWith(undefined)).subscribe(() =>
{
console.log('changed')
})
}
Run Code Online (Sandbox Code Playgroud)
这将立即触发订阅处理程序。
| 归档时间: |
|
| 查看次数: |
9165 次 |
| 最近记录: |