javascript - 如何在父组件中获取渲染后的子组件?

标签 javascript angular typescript

我的目标是只获取父组件中可见的子组件。

这是我的伪代码失败方法:

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/

相关文章:

javascript - 如何在基于 JavaScript 的经典 ASP 中生成 Excel 电子表格?

javascript - 如何拦截非 JSON 的响应

javascript - 使用 Angular-CLI 正确配置脚本

javascript - Angular +矩形+ typescript 装饰器错误

arrays - 订阅 Angular 6

javascript - 单击单选按钮时如何隐藏 li

javascript - 从子窗口访问父窗口的内容

javascript - AngularJS Controller 的命名问题

iframe - iframe 内的 Angular 2 触发插值

angular - 没有 UrlHelperService 的提供者