我要做个 弹窗组件,需要实现动态创建组件
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(); }
1.如需转载本站原创文章,请务必注明文章出处并附上链接,非常感谢。2.本站用于记录个人 工作、学习、生活,非商业网站,更多信息请 点击这里上一篇: css实现 元素宽高等比 宽高相同下一篇: javascript的防抖与节流