wsqww / devNote

开发笔记
3 stars 3 forks source link

Angular 动态组件 #70

Open wsqww opened 3 years ago

wsqww commented 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;
  }
}

分为一下几个步骤:

  1. 获取组件;
  2. 注册组件;componentFactoryResolver
  3. 获取 宿主元素的位置,并清空;viewContainerRef viewContainerRef.clear
  4. 实例化组件 插入到宿主位置,并获取 组件实例;viewContainerRef.createComponent
  5. 组件实例 设置数据;componentRef.instance