在角度2中,是否可以手动实例化组件A,然后将其传递并在组件B的模板中渲染?
是的,这是支持的.您需要一个ViewComponentRef,例如可以通过将其注入构造函数或使用@ViewChild(‘targetname’)查询和也可以注入的ComponentResolver来获取.
原文链接:https://www.f2er.com/angularjs/143248.html例如,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(); } } }