簡體   English   中英

angular 如何動態添加組件列表

[英]angular how to dynamically add a list of components

所以基本上我有一個按鈕,讓我可以選擇添加一個包含 2 個輸入的組件。 他們用戶可以多次添加這個組件。 但我嘗試了ComponentFactoryResolver但它當時只能添加一個組件。 在此處輸入圖片說明

當我按添加合同時,我將一個組件是一個包含輸入字段和標簽的卡片

使用*ngFor遍歷一個模型,然后顯示孩子

根據您想要實現的功能,您需要在已經提到的注釋中,在 TS 文件中創建模型,該文件將在 HTML 模板中使用*ngFor 將此與子組件結合使用,您可以輕松添加這些組件,例如單擊按鈕

TS 父母

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  // specifies the input data
  inputs = []

  addInput() {
    // Here you can specify the data
    this.inputs.push({});
  }
}

HTML 父級

<button (click)="addInput()">Add Input</button>
<app-child *ngFor="let input of inputs"></app-child>

HTML 子級

<p> Input: </p>
<input type="text">
  • 要指定您的子組件,您可以使用@Input()裝飾器。 如果您想顯示不同的表單或不同的元素,您可以在那里將input的數據傳遞給孩子。

供您參考: https ://stackblitz.com/edit/angular-hrdtcu

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM