動態創建組件
這篇文章我們將介紹在 Angular 中如何動態創建組件。
定義 AlertComponent 組件
首先,我們需要定義一個組件。
exe-alert.component.ts
import { Component, Input } from '@angular/core';@Component({ selector: "exe-alert", template: ` <h1>Alert {{type}}</h1> `,})export class AlertComponent { @Input() type: string = "success";}上面代碼中,我們定義了一個簡單的 alert 組件,該組件有一個輸入屬性 type ,用于讓用戶自定義提示的類型。我們的自定義組件最終是一個實際的 DOM 元素,因此如果我們需要在頁面中插入該元素,我們就需要考慮在哪里放置該元素。
創建組件容器
在 Angular 中放置組件的地方稱為 container 容器。接下來,我們將在 exe-app 組件中創建一個模板元素,此外我們使用模板變量的語法,聲明一個模板變量。接下來模板元素 <ng-template> 將會作為我們的組件容器,具體示例如下:
app.component.ts
import { Component } from '@angular/core';@Component({ selector: 'exe-app', template: ` <ng-template #alertContainer></ng-template> `})export class AppComponent { }友情提示:容器可以是任意的 DOM 元素或組件。
在 AppComponent 組件中,我們可以通過 ViewChild 裝飾器來獲取視圖中的模板元素,如果沒有指定第二個查詢參數,則默認返回的組件實例或相應的 DOM 元素,但這個示例中,我們需要獲取 ViewContainerRef 實例。
ViewContainerRef 用于表示一個視圖容器,可添加一個或多個視圖。通過 ViewContainerRef 實例,我們可以基于 TemplateRef 實例創建內嵌視圖,并能指定內嵌視圖的插入位置,也可以方便對視圖容器中已有的視圖進行管理。簡而言之,ViewContainerRef 的主要作用是創建和管理內嵌視圖或組件視圖。
根據以上需求,更新后的代碼如下:
import { Component, ViewChild, ViewContainerRef } from '@angular/core';@Component({ selector: 'exe-app', template: ` <ng-template #alertContainer></ng-template> `})export class AppComponent { @ViewChild("alertContainer", { read: ViewContainerRef }) container: ViewContainerRef;}動態創建組件
接下來,在 AppComponent 組件中,我們來添加兩個按鈕,用于創建 AlertComponent 組件。
import { Component, ViewChild, ViewContainerRef } from '@angular/core';@Component({ selector: 'exe-app', template: ` <ng-template #alertContainer></ng-template> <button (click)="createComponent('success')">Create success alert</button> <button (click)="createComponent('danger')">Create danger alert</button> `})export class AppComponent { @ViewChild("alertContainer", { read: ViewContainerRef }) container: ViewContainerRef;}
新聞熱點
疑難解答
圖片精選