In angular 2, is it possible to manually instantiate a component A, then pass it around and render in the template of component B?
Asked
Active
Viewed 3,005 times
7
-
Welcome to SO please check this [URL](http://stackoverflow.com/help)it will be helping you to raise your question content quality – Willie Cheng May 06 '16 at 02:57
1 Answers
0
Yes, that's supported. You need a ViewComponentRef
that can for example be acquired by injecting it to the constructor or using a @ViewChild('targetname')
query and a ComponentResolver
that also can be injected.
This code example from https://stackoverflow.com/a/36325468/217408 allows for example to add components dynamically with *ngFor
@Component({
selector: 'dcl-wrapper',
template: `<div #target></div>`
})
export class DclWrapper {
@ViewChild('target', {read: ViewContainerRef}) target;
@Input() type;
cmpRef:ComponentRef;
private isViewInitialized:boolean = false;
constructor(private resolver: ComponentResolver) {}
updateComponent() {
if(!this.isViewInitialized) {
return;
}
if(this.cmpRef) {
this.cmpRef.destroy();
}
this.resolver.resolveComponent(this.type).then((factory:ComponentFactory<any>) => {
this.cmpRef = this.target.createComponent(factory)
});
}
ngOnChanges() {
this.updateComponent();
}
ngAfterViewInit() {
this.isViewInitialized = true;
this.updateComponent();
}
ngOnDestroy() {
if(this.cmpRef) {
this.cmpRef.destroy();
}
}
}

Community
- 1
- 1

Günter Zöchbauer
- 623,577
- 216
- 2,003
- 1,567
-
1
-
Not sure what you mean. The more complete example in the linked answer shows how to pass data in and out. – Günter Zöchbauer Jul 30 '16 at 02:53