【问题标题】:How to get Child Components from ViewContainerRef - Angular 9?如何从 ViewContainerRef - Angular 9 获取子组件?
【发布时间】:2020-12-08 16:08:47
【问题描述】:

我在 viewContainerRef 中添加了动态组件 (ChildComponent.ts)。如果我使用索引来获取子组件 (viewContainerRef.get(0)),我可以像这样从 viewContainerRef 获取子组件数量viewContainerRef.get(0),它会返回 ViewRef 但我需要子组件如何执行此操作。

例子:

@ViewChild("cards_holder", { read: ViewContainerRef }) cards_holder: ViewContainerRef;

 const componentFactory = this.resolver.resolveComponentFactory( SimpleCardComponent);
const componentRef = this.cards_holder.createComponent(componentFactory);

for (let index = 0; index < this.cards_holder.length; index++) {
    console.log(this.cards_holder.get(index)) //It's Return ViewRef but i need SimpleCardComponent
}

谢谢。 Sabish.M

【问题讨论】:

    标签: angular angular9 angular-dynamic-components


    【解决方案1】:

    由于createComponent 返回组件引用,您可以像这样访问 SimpleCardComponent 实例:

    const componentRef = this.cards_holder.createComponent(componentFactory);
    const compInstance = <SimpleCardComponent>componentRef.instance;
    

    【讨论】:

    • 我希望你是泰米尔人。我来自蒂鲁内尔维利。可以在创建 Componenet 后从 ViewContinerRef 获取 ComponentRef。
    • createComponent 方法仅在 viewContainerRef 类中可用,但我认为不可能从 ViewRef 获取组件实例
    • @Sabish.M 你不能手动存储它们吗?类似:cards_holder.children = []; cards_holder.children.push(componentRef)?这样您就不会在创建后丢失引用。
    • 我知道这一点。我只是要求获取 componenetRef 而不将组件引用存储在任何地方。
    猜你喜欢
    • 2023-03-09
    • 2020-10-11
    • 2017-10-27
    • 2018-12-01
    • 2022-12-15
    • 2020-11-11
    • 2020-01-03
    • 2020-07-10
    • 1970-01-01
    相关资源
    最近更新 更多