[英]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.