模板驱动的表格将所有内容标记为已触摸-Angular 7 [英] Template Driven Form Mark All as touched - Angular 7

查看:112
本文介绍了模板驱动的表格将所有内容标记为已触摸-Angular 7的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用模板驱动的表单进行验证.当用户在最后一个必填字段上模糊时,我想将所有字段标记为已触摸.目前,我只能通过传递表格并单独完成每个字段来做到这一点.从研究中,我发现有一种方法可以执行MarkAllAsTocuhed,但它会引发错误.有没有更好/正确的方法可以使用Angular 7做到这一点.我还尝试了遍历控件,但是由于它是一个也不起作用的对象.

I am using template driven forms for validations. And I would like to Mark all fields as touched when the user blur on the last required field. currently I am only able to do this by passing the form and individually doing each field. From research I see there is a way to do MarkAllAsTocuhed but it's throwing an error. Is there a better/correct way to do this with Angular 7. I also tried looping through the controls but since it's an object that also does not work.

.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>

.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
 }
}

推荐答案

您可以尝试以下操作:

发现Object.keys可以处理此问题.

Found out that Object.keys can handle this.

 Object.keys(this.form.controls).forEach(key => {
      this.form.get(key).markAsTouched();
    });

对于Angular 8+,您可以使用:

For Angular 8+, you can use:

  Object.keys(this.form.controls).forEach(key => {
      this.form.controls[key].markAsTouched();
    });

这篇关于模板驱动的表格将所有内容标记为已触摸-Angular 7的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆