Open wsqww opened 3 years ago
看官方代码:点这里
关键代码:
export class { @ViewChild(AdDirective, {static: true}) adHost!: AdDirective; constructor(private componentFactoryResolver: ComponentFactoryResolver) { } ngOnInit() { this.loadComponent(); } loadComponent() { // 获取组件 this.currentAdIndex = (this.currentAdIndex + 1) % this.ads.length; const adItem = this.ads[this.currentAdIndex]; // 注册 组件 const componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component); // 获取 宿主元素的位置 const viewContainerRef = this.adHost.viewContainerRef; // 清空 宿主元素内容 viewContainerRef.clear(); // 实例化组件 插入到宿主位置,并获取 组件实例 const componentRef = viewContainerRef.createComponent<AdComponent>(componentFactory); // 组件实例 设置数据 componentRef.instance.data = adItem.data; } }
分为一下几个步骤:
componentFactoryResolver
viewContainerRef
viewContainerRef.clear
viewContainerRef.createComponent
componentRef.instance
看官方代码:点这里
关键代码:
分为一下几个步骤:
componentFactoryResolver
viewContainerRef
viewContainerRef.clear
viewContainerRef.createComponent
componentRef.instance