![](/img/trans.png)
[英]angular2 dynamic form with *ngFor, two-way-binding [(ngModel)] and form validation
[英]Angular 7 Dynamic Creating form with ngFor and ngModel with validation (or ngFrom)
我正在嘗試在Angular中創建一個類似輸入表單的表。
我目前的解決方案是這樣的:
HTML:
<form (ngSubmit)="doSomething()">
<table>
<thead>
<tr>First Name</tr>
<tr>Last Name</tr>
<tr>Phone Number</tr>
</thead>
<tbody>
<tr *ngFor="let person of team"></tr>
<td><input type="text" [(ngModel)]="person.first_name" [ngModelOptions]="{standalone: true}" required></td>
<td><input type="text" [(ngModel)]="person.last_name" [ngModelOptions]="{standalone: true}" required></td>
<td><input type="text" [(ngModel)]="person.phone" [ngModelOptions]="{standalone: true}" required></td>
</tbody>
</table>
<button (click)="addNewEntry()"></button>
<button type="submit">Submit</button>
TS:
team : new Array()
addNewEntry(){
this.team.push({
'first_name':'',
'last_name':'',
'phone':null})
}
doSomething(){
};
但是,如果我這樣做,“必需的”驗證器在單擊“提交”按鈕時不起作用。
我嘗試了幾種方法:
而不是設置[ngModelOptions] =“{standalone:true}” ,我嘗試了name ='person:{{$ index}}' 。 不行。
嘗試設置ngForm而不是使用ngModel ,使用formControlName 。 我無法弄清楚如何動態創建formControlName並驗證它們。
請問是否有辦法正確完成這項工作?
謝謝!
您最好的選擇是使用Angular ReactiveFormsModule。 ReactiveFormsModule支持FormArray,可以輕松執行驗證並獲取表單項值。
供參考,請查看:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.