Angular組件的高級玩法

如果想要手動創(chuàng)建組件,需要在app.module.ts里面加一個配置項(xiàng),例如需要手動創(chuàng)建ChildOneComponent實(shí)例,添加到entryComponents告訴脫機(jī)模板編譯器編譯它們并為它們創(chuàng)建工廠

entryComponents:[ChildOneComponent]

離線模板編譯器(OTC)只生成實(shí)際使用的組件。如果組件不直接用于模板,OTC不知道是否需要編譯。有了entryComponents,你可以告訴OTC也編譯這些組件,以便在運(yùn)行時可用

構(gòu)造函數(shù)里面需要注入組件工廠解析器ComponentFactoryResolver

constructor(private resolver: ComponentFactoryResolver) { }
./test-dynamic-component/test-dynamic-component.component.ts

import { Component, OnInit, ViewChild, ViewContainerRef, ComponentFactoryResolver, ComponentRef } from '@angular/core';
import { ChildOneComponent } from './child-one/child-one.component';

@Component({
  selector: 'test-dynamic-component',
  templateUrl: './test-dynamic-component.component.html',
  styleUrls: ['./test-dynamic-component.component.scss']
})
export class TestDynamicComponentComponent implements OnInit {
  @ViewChild('dyncontainer', { read: ViewContainerRef })
  dyncontainer: ViewContainerRef

  comp1: ComponentRef<ChildOneComponent>;

  constructor(private resolver: ComponentFactoryResolver) { }

  ngOnInit() {
  }

  ngAfterContentInit() {
    console.log('動態(tài)的創(chuàng)建組件的實(shí)例...');
    //定義變量拿到解析的子組件
    const childComp = this.resolver.resolveComponentFactory(ChildOneComponent);
    //在標(biāo)識的容器內(nèi)創(chuàng)建解析好的子組件,拿到這個DOM節(jié)點(diǎn)
    this.comp1 = this.dyncontainer.createComponent(childComp);
    //通過DOM節(jié)點(diǎn)的實(shí)例,可以設(shè)置屬性
    this.comp1.instance.title = '父組件動態(tài)賦值的標(biāo)題';
    //訂閱子組件發(fā)送過來的事件
    this.comp1.instance.myEvent.subscribe((data) => {
      console.log(data);
    });

    // let comp2 = this.dyncontainer.createComponent(childComp);
    // comp2.instance.title = '我是第2個動態(tài)組件';
    // let comp3 = this.dyncontainer.createComponent(childComp);
    // comp3.instance.title = '我是第3個動態(tài)組件';
    // let comp4 = this.dyncontainer.createComponent(childComp, 0);
    // comp4.instance.title = '我是第4個動態(tài)組件';
  }

  public delComp():void{
    this.comp1.destroy();
  }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容