1.檔案目錄
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiNx8FesU2cfdGLwczX0xiRGZkRGZ0Xy9GbvNGL58VZ6l2cs0TPRRmdSdVYoVzVhRjWIJWQClGVF5UMR9Fd4VGdsATNfd3bkFGazxycykFaKdkYzZUbapXNXlleSdVY2pESa9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnL1MzN2cDNxEmM0cDNiVmNiF2N4QjM0kzMiZDO0EGM4U2Lc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
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-動态元件