@ViewChild(ComponentType) comp!: ComponentType;
ngAfterViewInit() {
console.log('ComponentType instance', comp);
}
为了获得子组件的实例,我知道可以使用ViewChild
,如上面所示。它适用于静态添加的组件,但是如果像演示的在StackBlitz上那样在动态添加的组件上使用它,就会在ngAfterViewInit
上得不到定义。
获得动态加载子组件实例的正确方法是什么?
发布于 2022-11-21 06:59:16
这是不可能的Angular不允许使用ViewChild/ViewChildren动态创建子级。见https://github.com/angular/angular/issues/45771和https://stackoverflow.com/a/43957857/4472932。
但是,您可以将创建的子程序保存在服务中作为示例。组件自定义为const componentRef = viewContainerRef.createComponent<AdComponent>(adItem.component);
componentRef。所以ViewChildren/ViewChild的子类和componentRef是一样的。
你好,弗洛
https://stackoverflow.com/questions/74518072
复制相似问题