在angular 2中,是否可以手动实例化一个组件A,然后将其传递并在组件B的模板中渲染?
最佳答案
是的,这是受支持的。您需要一个 ViewComponentRef
,例如可以通过将其注入(inject)构造函数或使用 @ViewChild('targetname')
查询和 ComponentResolver
也可以注入(inject)。
此代码示例来自 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();
}
}
}
关于angular - 是否可以在 Angular 2 中手动实例化组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37063455/