天天看點

angular中動态建立元件

1.檔案目錄

angular中動态建立元件

2.核心代碼

app.component.html

<h1 #msgContainer>我是Container</h1>
<button (click)="createComponent()">建立元件</button>

<!-- <h1>我是Container 2</h1>
<ng-template #msgContainer></ng-template>
<button (click)="createComponent()">建立元件2</button> -->
           

app.component.ts

import { Component, ViewChild, ViewContainerRef, ComponentFactoryResolver, ComponentFactory, ComponentRef } from '@angular/core';
import { MsgComponentComponent } from './components/msg-component/msg-component.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  entryComponents: [MsgComponentComponent]
})
export class AppComponent {
  // 引用動态的子元件
  @ViewChild('msgContainer', {read: ViewContainerRef}) container;
  // 動态元件變量
  componentRef:ComponentRef<MsgComponentComponent>;
  // 注入工廠解析器
  constructor(private reslover: ComponentFactoryResolver) {}
  createComponent() {
    //清空元件
    this.clearMsgContainer();
    // 建立一個元件工廠
    const factory: ComponentFactory<MsgComponentComponent> = this.reslover.resolveComponentFactory(MsgComponentComponent);
    this.componentRef = this.container.createComponent(factory);

    console.log('componentRef', this.componentRef);
    console.log('componentRef.instance', this.componentRef.instance);

    this.componentRef.instance.type = Math.random() + '';

  }
  // 清空元件
  clearMsgContainer() {
    this.container.clear();
  }
  // 銷毀元件
  ngOnDestroy() {
    console.log('ngOnDestroy');
    this.componentRef.destroy(); 
  }
}

           

msg.component.html

msg.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-msg-component',
  templateUrl: './msg-component.component.html',
  styleUrls: ['./msg-component.component.css']
})
export class MsgComponentComponent implements OnInit {
  public type:string = '123';
  public testDynamicVar = '';

  constructor() { }

  ngOnInit(): void {
    this.testDynamicFuntiocn();
  }

  testDynamicFuntiocn() {
    this.testDynamicVar = 'test';
  }

}

           

3.學習位址

動态元件

csdn-動态元件