@H_403_3@
我试图在angular docs中显示一个类似(不完全)的动态组件.
@H_502_24@解决方法
我有一个带有viewContainerRef的动态指令
@Directive({ selector: '[dynamicComponent]' }) export class DynamicComponentDirective { constructor(public viewContainerRef: ViewContainerRef) { } }
摘自组件代码
@ViewChild(DynamicComponentDirective) adHost: DynamicComponentDirective; .. ngAfterViewInit() { let componentFactory = null; console.log(component); componentFactory = this.componentFactoryResolver.resolveComponentFactory(component); // this.adHost.viewContainerRef.clear(); const viewContainerRef = this.adHost.viewContainerRef; viewContainerRef.createComponent(componentFactory); }
最后添加< ng-template dynamicComponent>< / ng-template>在模板中
你可以采取这种方法:
不要创建指令,而是提供一个Id到ng模板
不要创建指令,而是提供一个Id到ng模板
<ng-template #dynamicComponent></ng-template>
在组件类中使用@ViewChild装饰器
@ViewChild('dynamicComponent',{ read: ViewContainerRef }) myRef ngAfterViewInit() { const factory = this.componentFactoryResolver.resolveComponentFactory(component); const ref = this.myRef.createComponent(factory); ref.changeDetectorRef.detectChanges(); }
@H_403_3@