问题
In angular 2, is it possible to manually instantiate a component A, then pass it around and render in the template of component B?
回答1:
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();
}
}
}
来源:https://stackoverflow.com/questions/37063455/is-it-possible-to-manually-instantiate-component-in-angular-2