Fla*_*ash 3 html forms validation angular-material angular
我正在使用模板驱动的表单进行验证。当用户在最后一个必填字段上模糊时,我想将所有字段标记为已触摸。目前我只能通过传递表单并单独执行每个字段来做到这一点。从研究中我看到有一种方法可以执行 MarkAllAsTocuhed 但它会引发错误。有没有更好/正确的方法来使用 Angular 7 来做到这一点。我也尝试通过控件循环,但因为它是一个也不起作用的对象。
.HTML
<form #myForm="ngForm">
<mat-form-field class="input-field">
<input #field1="ngModel" name="name1"
[(ngModel)]="fieldOne" type="text" matInput placeholder="Field 1" required>
</mat-form-field>
<mat-form-field class="input-field">
<input #field2="ngModel" name="name2"
[(ngModel)]="fieldTwo" type="text" matInput placeholder="Field 2" required>
</mat-form-field>
<mat-form-field class="input-field">
<input #field2="ngModel" name="name3"
[(ngModel)]="fieldThree" type="text" matInput placeholder="Field 3" required>
</mat-form-field>
<mat-form-field class="input-field">
<input #field3="ngModel" name="name4"
[(ngModel)]="fieldFour" type="text" matInput placeholder="Field 4"
(blur)="touchAllFields(myForm.form)" required>
</mat-form-field>
</form>
Run Code Online (Sandbox Code Playgroud)
.TS
touchAllFields(form){
//Working Version
form.controls.name1.markAsTouched();
form.controls.name2.markAsTouched();
form.controls.name3.markAsTouched();
form.controls.name4.markAsTouched();
form.controls.name5.markAsTouched();
form.controls.name6.markAsTouched();
form.controls.name7.markAsTouched();
form.controls.name8.markAsTouched();
//Failed Attempt
form.controls.markAllAsTouched(); //typeError: form.controls.markAllAsTouched is not a function
//Failed Attempt
for(var i = 0; i < form.controls.length; i++){
form.controls[i].markAllAsTouched(); //Failed since its an object and not an array
}
}
Run Code Online (Sandbox Code Playgroud)
ngForm
本身没有markAllAsTouched
方法,因为它不是FormGroup
或FormArray
。但是,NgForm
有一个formGroup
可通过.form
or .control
- source访问的实例。这从 Angular2 到当前最新版本 (Angular10) 一直可用
所以你的问题的正确答案应该如下:
form.form.markAllAsTouched();
Run Code Online (Sandbox Code Playgroud)
或者
form.control.markAllAsTouched();
Run Code Online (Sandbox Code Playgroud)
你可以试试这个:
发现 Object.keys 可以处理这个问题。
Object.keys(this.form.controls).forEach(key => {
this.form.get(key).markAsTouched();
});
Run Code Online (Sandbox Code Playgroud)
对于 Angular 8+,您可以使用:
Object.keys(this.form.controls).forEach(key => {
this.form.controls[key].markAsTouched();
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3519 次 |
最近记录: |