angular 动态创建组件

chat

我要做个 弹窗组件,需要实现动态创建组件

html 模板:

 <button (click)="createComponentFactory('hhe')">动态创建组件 测试</button>
  <button (click)="destroyComponent()">destroy</button>

首先  导入组件 以及相关依赖



import {Component, ComponentFactory, ComponentFactoryResolver, ComponentRef, OnDestroy, ViewChild, ViewContainerRef} from '@angular/core';
import { ElementRef} from '@angular/core';
import {PopupComponent} from './share/popup/popup.component';
 @ViewChild('alertContainer', { read: ViewContainerRef }) container: ViewContainerRef;
  componentRef: ComponentRef<PopupComponent>;
  constructor(private el: ElementRef, private resolver: ComponentFactoryResolver) {
  }

 
ngOnDestroy() {
    this.destroyComponent();
  }
  createComponentFactory(type) {
    this.container.clear();
    const factory: ComponentFactory<PopupComponent> = this.resolver.resolveComponentFactory(PopupComponent);
    this.componentRef = this.container.createComponent(factory);
    this.componentRef.instance.type = type;
    console.log('componentRef', this.componentRef);

    this.componentRef.instance.close.subscribe(event => {
      console.log(event);
      this.destroyComponent();
    } );

  }

  destroyComponent() {
    this.componentRef.destroy();
  }

版权声明:
作者:东明兄
链接:https://blog.crazyming.com/note/721/
来源:CrazyMing
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
海报
angular 动态创建组件
我要做个 弹窗组件,需要实现动态创建组件 html 模板: <button (click)="createComponentFactory('hhe')">动态创建组件 测试</button&……
<<上一篇
下一篇>>
chat