在angular 2中,是否可以手动实例化组件a,然后将其传递并在组件B的模板中渲染?
是的,支持。您需要一个ViewComponentRef
,例如可以通过将其注入构造函数或使用@ViewChild('targetname')
查询来获取,也可以注入ComponentResolver
。
此代码示例来自https://stackoverflow.com/a/36325468/217408允许例如使用*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();
}
}
}