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