【发布时间】:2020-06-24 11:53:14
【问题描述】:
如何验证特定的
ngModels角度
例如:我有一个表,我想在其中仅验证 ngModels 的第二行
我可以使用验证完整形式(全部ngModels)
this.myForm.valid.
并且还要验证特定的ngModels 我可以遍历this.myForm.controls 并验证特定的。
是否有另一种方法来验证而不是循环遍历整个表单控件?
下面的完整示例
TS
@ViewChild(NgForm, { static: false }) myForm: NgForm;
employeesData = [{id:"1",firstName:"Tom",lastName:"Cruise",photo:"https://pbs.twimg.com/profile_images/735509975649378305/B81JwLT7.jpg"},{id:"2",firstName:"Maria",lastName:null,photo:"https://pbs.twimg.com/profile_images/3424509849/bfa1b9121afc39d1dcdb53cfc423bf12.jpeg"},{id:"3",firstName:"James",lastName:null,photo:"https://pbs.twimg.com/profile_images/664886718559076352/M00cOLrh.jpg"}];
save() {
//This helps to validate all fields
console.log(this.myForm.valid);
//This contains all form keys - so I can loop through each and validate
console.log(this.myForm.controls);
}
}
HTML
<form #myForm="ngForm">
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
</tr>
<tr *ngFor="let employee of employeesData; let i=index">
<td>
<input type="text" [(ngModel)]="employee.firstName" [name]="'firstName'+i" required>
</td>
<td>
<input type="text" [(ngModel)]="employee.lastName" [name]="'lastName'+i" required>
</td>
<td>
<button (click)="save()">Save</button>
</td>
</tr>
</table>
</form>
是否有更好的方法来验证特定的 ngModel?
我怎样才能只验证一行?
【问题讨论】:
-
你能在 stackblitz 中重现你的问题吗
标签: angular forms validation