【发布时间】:2020-02-12 00:34:48
【问题描述】:
目标是了解如何获取对任何嵌套组件的引用。这是具有 4 个嵌套组件的示例。 A 将 B 作为子组件,B 将 C 作为其子组件,C 将 D 作为动态/运行时创建的子组件。所以问题是Angular是否提供了开箱即用的解决方案:
A 组件如何获取 C 组件的引用?
A 组件如何获取在运行时创建的 D 组件的引用?
@Component({
selector: 'A',
template: `<B></B>`
})
export class A {}
@Component({
selector: 'B',
template: `<C></C>`
})
export class B {}
@Component({
selector: 'C',
template: `<div>C Component</div> <div #container></div>`
})
export class C implements OnInit{
@ViewChild('container')
container: TemplateRef<any>;
constructor(private resolver:ComponentFactoryResolver){}
ngOnInit() {
const DFactory= this.resolver.resolveComponentFactory(D);
this.container.createComponent(DFactory);
}
}
@Component({
selector: 'D',
template: `<div>D component</div>`
})
export class D{}
【问题讨论】:
-
A 组件如何获取 C 组件的引用?组件 B 知道 Component 并且应该公开 ViewChild 组件 C 的属性,因此组件 A 应该有一个 ViewChild 绑定到组件 B。通过 viewchildB 组件 A 应该可以获取组件 B 中的 viewchild C 的属性。
-
A 组件如何获取运行时创建的 D 组件的引用?从最后一个问题开始,在组件 c 中添加一个新的 piublic 属性,该属性将填充
createComponent函数的结果(返回一个 ComponentRef 对象)。 angular.io/api/core/ViewContainerRef#createComponent -
不确定是否可以快速尝试此解决方案
标签: angular angular-components angular8