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.
}
}
I think about some manual way to resolve the ViewChild instead of using the decorators. Some Ideas?
Thanks a lot.
Descriptionlink. Can contain host views (created by instantiating a component with the createComponent() method), and embedded views (created by instantiating a TemplateRef with the createEmbeddedView() method).
Get ViewContainerRef with ViewChild: We can use the ViewChild decorator to grab any element in our view and read him as ViewContainerRef . In this example, the container element is the “div” element, and the template will be inserted as a sibling of this “div.”
The @ViewChild decorator allows us to inject into a component class references to elements used inside its template, that's what we should use it for. Using @ViewChild we can easily inject components, directives or plain DOM elements.
ViewContainerRef represents a container where one or more views can be attached. The first thing to mention here is that any DOM element can be used as a view container. What's interesting is that Angular doesn't insert views inside the element, but appends them after the element bound to ViewContainer .
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:
in the html file create:
<div id="test"></div>
in your component create:
let nodeElement = document.getElementById("test");
let compFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
let component = compFactory.create(this.viewContainerRef.injector, null, nodeElement);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With