我的目标是只获取父组件中可见的子组件。
这是我的伪代码失败方法:
parent.component.html
<parent (click)="changeVisibility()">
<child *ngIf="visible1"></child>
<child *ngIf="visible2"></child>
<child *ngIf="visible3"></child>
</parent-component>
父组件.ts
@ViewChildren(ChildComponent) childs: ChildComponent[];
visible1: boolean = true;
visible2: boolean = true;
visible3: boolean = true;
changeVisibility(){
this.visible2 = false;
}
希望能很好地解释我的问题。提前致谢。
最佳答案
ViewChildren
的类型是QueryList
@ViewChildren(ChildComponent) childs: QueryList<ChildComponent>;
有一个 Observable for changes
并且它会为更改发出一个事件。
this.childs.changes.subscribe(e => {
console.log('changes', e);
// Write your logic ...
// i.e:
// e.length
// e.forEach(child => { ... })
})
关于javascript - 如何在父组件中获取渲染后的子组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59412785/