Reputation: 191
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.
Upvotes: 12
Views: 11077
Reputation: 541
Dynamically Created Component
export class DashPanelComponent implements OnInit {
@ViewChild('dashpanelpos', { read: ViewContainerRef }) dashPanelPosition?: ElementRef;
constructor() { }
ngOnInit() { }
}
To access ViewContainerRef
this.dashPanel = this.renderComp({}, this.contentMappings["dash_panel"], container);
this.viewContainerRef = this.dashPanel.instance["dashPanelPosition"]);
dashPanelPosition
is instance of DashPanelComponent
.
Upvotes: 0
Reputation: 887
Your question can be answered if you read those two articles, it solved it for me:
The second article contains working angular examples on Github where you can check out working examples of dynamically created Components in 4 different ways.
Upvotes: -1
Reputation: 1175
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);
Upvotes: 2