【发布时间】:2016-05-06 02:51:33
【问题描述】:
在angular 2中,是否可以手动实例化一个组件A,然后将其传递并渲染到组件B的模板中?
【问题讨论】:
-
欢迎来到 SO,请查看此URL它将帮助您提高您的问题内容质量
标签: angular angular2-components
在angular 2中,是否可以手动实例化一个组件A,然后将其传递并渲染到组件B的模板中?
【问题讨论】:
标签: angular angular2-components
是的,这是受支持的。您需要一个 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();
}
}
}
【讨论】: