angular 动态创建组件

Daming 2018-12-26
0条评论 1,014 次浏览
Daming 2018-12-260条评论 1,014 次浏览

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

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();
  }

0

发表评论

电子邮件地址不会被公开。