簡體   English   中英

在 DOM 中添加動態組件

[英]Add dynamic component in the DOM

我在 Angular 中有一個項目,其中我為一個組件創建了一個包含多個字段的對話框。 我想要的是將此對話框用於其他組件,但數據量會有所不同。

這是我的 dialog.component.html:

<div class="dialog-container">

  <mat-form-field>
    <input matInput placeholder="Name" [(ngModel)]="data.name">
  </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="Phone" [(ngModel)]="data.phoneNumber">
  </mat-form-field>

  <mat-form-field>
    <input matInput placeholder="Email" [(ngModel)]="data.email">
  </mat-form-field>
</div>

我想知道是否可以只創建一個 mat-form 組件並顯示盡可能多的組件,並將我想要生成的字段數傳遞給它。

這就是我希望 dialog.component.html 包含的內容,以實現與上述相同(我不知道這是否可能):

<div class="dialog-container">

  <mat-form-field>
    <input matInput placeholder={{place}} [(ngModel)]={{data}}>
  </mat-form-field>
</div>

僅從一個mat-form-field是否可以顯示與第一個示例相同的結果?

您可以創建一個自定義指令:

import { Directive, Input } from '@angular/core';
import { NgForOf } from '@angular/common';

@Directive({
  selector: '[ngFor][ngForRepeat]'
})
export class NgForRepeat<T> extends NgForOf<T> {
  @Input() set ngForRepeat(repeat: number) {
    this.ngForOf = new Array(repeat >= 0 ? repeat : 0);
  }
}

並在您的模板中按以下方式使用它:

<ng-container *ngForRepeat="3">
  <mat-form-field>
    <input matInput placeholder={{place}} [(ngModel)]={{data}}>
  </mat-form-field>
</ng-container>

暫無
暫無

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

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