国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

詳解Angular 4.x 動態創建組件

2024-05-06 15:18:00
字體:
來源:轉載
供稿:網友

動態創建組件

這篇文章我們將介紹在 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;}            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 威信县| 和静县| 阿巴嘎旗| 英吉沙县| 汾西县| 宁武县| 时尚| 香格里拉县| 敦煌市| 哈尔滨市| 长乐市| 宣汉县| 竹北市| 江门市| 兴山县| 绥芬河市| 万山特区| 富裕县| 龙南县| 岳西县| 张家界市| 玛沁县| 开平市| 永昌县| 呼图壁县| 琼结县| 繁峙县| 阿巴嘎旗| 高陵县| 巴彦县| 南召县| 柳州市| 明水县| 雷山县| 陇南市| 纳雍县| 张北县| 蓬安县| 枣庄市| 图们市| 喜德县|