成角度,从动态创建的组件获取ViewChild/ViewContainerRef [英] Angular, get ViewChild / ViewContainerRef from dynamic created Component
本文介绍了成角度,从动态创建的组件获取ViewChild/ViewContainerRef的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法从动态创建的组件中获取ViewContainerRef? 我动态创建的组件内部有一个ngContent元素,我想在动态创建后填充它.
is there a way to get the ViewContainerRef from a dynamic created component? My dynamic created component has an ngContent element inside, which i want to fill after the dynamic creation.
export class Example {
@ViewChild('content', { read: ViewContainerRef }) //normal way
content: ViewContainerRef;
...
ngAfterViewInit(){
let box1=this.content.createComponent(this.boxFactory);
box1.instance.title="Dynamic (1)";
// HERE: the box1 has a ng-content area which i want to fill.
}
}
我考虑了一些手动方法来解决ViewChild问题,而不是使用装饰器.有什么想法吗?
I think about some manual way to resolve the ViewChild instead of using the decorators. Some Ideas?
非常感谢.
推荐答案
我也不确定如何动态添加viewchild.但是,如果您需要动态ViewContainerRef,则可以尝试使用以下解决方案:
I am not sure as well how to add viewchild dynamically. however, if dynamic ViewContainerRef is what you want, you can try using this solution:
在html文件中创建:
in the html file create:
<div id="test"></div>
在您的组件中创建:
let nodeElement = document.getElementById("test");
let compFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
let component = compFactory.create(this.viewContainerRef.injector, null, nodeElement);
这篇关于成角度,从动态创建的组件获取ViewChild/ViewContainerRef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文