114

我无法找出如何将所有表单的字段标记为已触摸。主要问题是,如果我不触摸字段并尝试提交表单 - 验证错误不会显示出来。我的控制器中有那段代码的占位符。
我的想法很简单:

  1. 用户点击提交按钮
  2. 所有字段都标记为已触摸
  3. 错误格式化程序重新运行并显示验证错误

如果有人有其他想法如何在提交时显示错误,而不实施新方法 - 请分享。谢谢!


我的简化形式:

<form class="form-horizontal" [formGroup]="form" (ngSubmit)="onSubmit(form.value)">
    <input type="text" id="title" class="form-control" formControlName="title">
    <span class="help-block" *ngIf="formErrors.title">{{ formErrors.title }}</span>
    <button>Submit</button>
</form>

我的控制器:

import {Component, OnInit} from '@angular/core';
import {FormGroup, FormBuilder, Validators} from '@angular/forms';

@Component({
  selector   : 'pastebin-root',
  templateUrl: './app.component.html',
  styleUrls  : ['./app.component.css']
})
export class AppComponent implements OnInit {
  form: FormGroup;
  formErrors = {
    'title': ''
  };
  validationMessages = {
    'title': {
      'required': 'Title is required.'
    }
  };

  constructor(private fb: FormBuilder) {
  }

  ngOnInit(): void {
    this.buildForm();
  }

  onSubmit(form: any): void {
    // somehow touch all elements so onValueChanged will generate correct error messages

    this.onValueChanged();
    if (this.form.valid) {
      console.log(form);
    }
  }

  buildForm(): void {
    this.form = this.fb.group({
      'title': ['', Validators.required]
    });
    this.form.valueChanges
      .subscribe(data => this.onValueChanged(data));
  }

  onValueChanged(data?: any) {
    if (!this.form) {
      return;
    }

    const form = this.form;

    for (const field in this.formErrors) {
      if (!this.formErrors.hasOwnProperty(field)) {
        continue;
      }

      // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.touched && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          if (!control.errors.hasOwnProperty(key)) {
            continue;
          }
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }
}
4

19 回答 19

174

Angular 8你可以简单地使用

this.form.markAllAsTouched();

将控件及其后代控件标记为已触摸。

抽象控制文档

于 2019-05-22T18:53:35.747 回答
164

以下函数通过表单组中的控件递归并轻轻触摸它们。因为控件字段是一个对象,所以代码在表单组的控件字段上调用 ​​Object.values()。

  /**
   * Marks all controls in a form group as touched
   * @param formGroup - The form group to touch
   */
  private markFormGroupTouched(formGroup: FormGroup) {
    (<any>Object).values(formGroup.controls).forEach(control => {
      control.markAsTouched();

      if (control.controls) {
        this.markFormGroupTouched(control);
      }
    });
  }
于 2017-05-24T06:42:14.160 回答
14

关于@masterwork 的回答。我尝试了该解决方案,但是当函数尝试在 FormGroup 内递归挖掘时出现错误,因为在这一行传递了 FormControl 参数,而不是 FormGroup:

control.controls.forEach(c => this.markFormGroupTouched(c));

这是我的解决方案

markFormGroupTouched(formGroup: FormGroup) {
 (<any>Object).values(formGroup.controls).forEach(control => {
   if (control.controls) { // control is a FormGroup
     markFormGroupTouched(control);
   } else { // control is a FormControl
     control.markAsTouched();
   }
 });
}
于 2018-01-23T15:42:57.760 回答
9

从 Angular v8 开始,您可以借助该方法内置此功能markAllAsTouched

例如,您可以像这样使用它

form.markAllAsTouched();

请参阅官方文档:https ://angular.io/api/forms/AbstractControl#markallastouched

于 2019-06-20T09:03:31.560 回答
8

遍历表单控件并将它们标记为已触摸也可以:

for(let i in this.form.controls)
    this.form.controls[i].markAsTouched();
于 2018-01-07T14:32:40.443 回答
3

这是我的解决方案

      static markFormGroupTouched (FormControls: { [key: string]: AbstractControl } | AbstractControl[]): void {
        const markFormGroupTouchedRecursive = (controls: { [key: string]: AbstractControl } | AbstractControl[]): void => {
          _.forOwn(controls, (c, controlKey) => {
            if (c instanceof FormGroup || c instanceof FormArray) {
              markFormGroupTouchedRecursive(c.controls);
            } else {
              c.markAsTouched();
            }
          });
        };
        markFormGroupTouchedRecursive(FormControls);
      }
于 2017-08-06T10:37:19.100 回答
2

我遇到了这个问题,但找到了这样做的“正确”方式,尽管它不在我找到的任何 Angular 教程中。

在您的 HTML 中,在form标签上,添加模板驱动表单示例使用的相同模板引用变量#myVariable='ngForm'(“hashtag”变量),以及响应式表单示例使用的内容:

<form [formGroup]="myFormGroup" #myForm="ngForm" (ngSubmit)="submit()">

现在您可以myForm.submitted在模板中访问,您可以使用它来代替(或除此之外)myFormGroup.controls.X.touched

<div *ngIf="myForm.submitted" class="text-error"> <span *ngIf="myFormGroup.controls.myFieldX.errors?.badDate">invalid date format</span> <span *ngIf="myFormGroup.controls.myFieldX.errors?.isPastDate">date cannot be in the past.</span> </div>

知道那myForm.form === myFormGroup是真的……只要你不忘记那="ngForm"部分。如果#myForm单独使用,它将不起作用,因为 var 将设置为 HtmlElement 而不是驱动该元素的指令。

根据 Reactive Forms 教程,知道这myFormGroup在组件的打字稿代码中是可见的,但myForm不是,除非你通过方法调用将它传递submit(myForm)submit(myForm: NgForm): void {...}. (注意NgForm在打字稿中的标题大写,但在 HTML 中是驼峰式的。)

于 2017-06-11T00:32:27.340 回答
1

没有递归的解决方案

对于那些担心性能的人,我提出了一个不使用递归的解决方案,尽管它仍然迭代所有级别的所有控件。

 /**
  * Iterates over a FormGroup or FormArray and mark all controls as
  * touched, including its children.
  *
  * @param {(FormGroup | FormArray)} rootControl - Root form
  * group or form array
  * @param {boolean} [visitChildren=true] - Specify whether it should
  * iterate over nested controls
  */
  public markControlsAsTouched(rootControl: FormGroup | FormArray,
    visitChildren: boolean = true) {

    let stack: (FormGroup | FormArray)[] = [];

    // Stack the root FormGroup or FormArray
    if (rootControl &&
      (rootControl instanceof FormGroup || rootControl instanceof FormArray)) {
      stack.push(rootControl);
    }

    while (stack.length > 0) {
      let currentControl = stack.pop();
      (<any>Object).values(currentControl.controls).forEach((control) => {
        // If there are nested forms or formArrays, stack them to visit later
        if (visitChildren &&
            (control instanceof FormGroup || control instanceof FormArray)
           ) {
           stack.push(control);
        } else {
           control.markAsTouched();
        }
      });
    }
  }

此解决方案适用于 FormGroup 和 FormArray。

你可以在这里玩它:angular-mark-as-touched

于 2019-01-24T09:37:32.053 回答
1

我遇到了同样的问题,但我不想用处理这个问题的代码“污染”我的组件。特别是因为我需要以多种形式使用它,并且我不想在各种场合重复代码。

因此,我创建了一个指令(使用到目前为止发布的答案)。该指令装饰了 NgForm 的 -Method onSubmit:如果表单无效,它会将所有字段标记为已触摸并中止提交。否则,通常的 onSubmit-Method 会正常执行。

import {Directive, Host} from '@angular/core';
import {NgForm} from '@angular/forms';

@Directive({
    selector: '[appValidateOnSubmit]'
})
export class ValidateOnSubmitDirective {

    constructor(@Host() form: NgForm) {
        const oldSubmit = form.onSubmit;

        form.onSubmit = function (): boolean {
            if (form.invalid) {
                const controls = form.controls;
                Object.keys(controls).forEach(controlName => controls[controlName].markAsTouched());
                return false;
            }
            return oldSubmit.apply(form, arguments);
        };
    }
}

用法:

<form (ngSubmit)="submit()" appValidateOnSubmit>
    <!-- ... form controls ... -->
</form>
于 2017-12-10T04:08:14.867 回答
1

这是我实际使用的代码。

validateAllFormFields(formGroup: any) {
    // This code also works in IE 11
    Object.keys(formGroup.controls).forEach(field => {
        const control = formGroup.get(field);

        if (control instanceof FormControl) {
            control.markAsTouched({ onlySelf: true });
        } else if (control instanceof FormGroup) {               
            this.validateAllFormFields(control);
        } else if (control instanceof FormArray) {  
            this.validateAllFormFields(control);
        }
    });
}    

于 2017-12-29T15:05:37.170 回答
1

这段代码对我有用:

markAsRequired(formGroup: FormGroup) {
  if (Reflect.getOwnPropertyDescriptor(formGroup, 'controls')) {
    (<any>Object).values(formGroup.controls).forEach(control => {
      if (control instanceof FormGroup) {
        // FormGroup
        markAsRequired(control);
      }
      // FormControl
      control.markAsTouched();
    });
  }
}
于 2018-01-23T15:33:37.867 回答
1

根据@masterwork

角度版本 8 的打字稿代码

private markFormGroupTouched(formGroup: FormGroup) {
    (Object as any).values(formGroup.controls).forEach(control => {
      control.markAsTouched();
      if (control.controls) {
        this.markFormGroupTouched(control);
      }
    });   }
于 2020-03-29T14:29:28.737 回答
1
onSubmit(form: any): void {
  if (!this.form) {
    this.form.markAsTouched();
    // this.form.markAsDirty(); <-- this can be useful 
  }
}
于 2016-11-10T14:42:14.317 回答
0

我完全理解OP的挫败感。我使用以下内容:

实用功能

/**
 * Determines if the given form is valid by touching its controls 
 * and updating their validity.
 * @param formGroup the container of the controls to be checked
 * @returns {boolean} whether or not the form was invalid.
 */
export function formValid(formGroup: FormGroup): boolean {
  return !Object.keys(formGroup.controls)
    .map(controlName => formGroup.controls[controlName])
    .filter(control => {
      control.markAsTouched();
      control.updateValueAndValidity();
      return !control.valid;
    }).length;
}

用法

onSubmit() {
  if (!formValid(this.formGroup)) {
    return;
  }
  // ... TODO: logic if form is valid.
}

请注意,此功能尚不适合嵌套控件。

于 2017-05-28T06:36:07.270 回答
0

我制作了一个版本,对所提供的答案进行了一些更改,对于那些使用 angular 版本 8 之前的版本的人,我想与那些有用的人分享。

实用功能:

import {FormControl, FormGroup} from "@angular/forms";

function getAllControls(formGroup: FormGroup): FormControl[] {
  const controls: FormControl[] = [];
  (<any>Object).values(formGroup.controls).forEach(control => {
    if (control.controls) { // control is a FormGroup
      const allControls = getAllControls(control);
      controls.push(...allControls);
    } else { // control is a FormControl
      controls.push(control);
    }
  });
  return controls;
}

export function isValidForm(formGroup: FormGroup): boolean {
  return getAllControls(formGroup)
    .filter(control => {
      control.markAsTouched();
      return !control.valid;
    }).length === 0;
}

用法:

onSubmit() {
 if (this.isValidForm()) {
   // ... TODO: logic if form is valid
 }
}
于 2020-02-21T20:13:15.563 回答
0
    /**
    * Marks as a touched
    * @param { FormGroup } formGroup
    *
    * @return {void}
    */
    markFormGroupTouched(formGroup: FormGroup) {
        Object.values(formGroup.controls).forEach((control: any) => {

            if (control instanceof FormControl) {
                control.markAsTouched();
                control.updateValueAndValidity();

            } else if (control instanceof FormGroup) {
                this.markFormGroupTouched(control);
            }
        });
    }
于 2019-08-13T10:51:57.533 回答
0

这是我的做法。在按下提交按钮(或触摸表单)之前,我不希望显示错误字段。

import {FormBuilder, FormGroup, Validators} from "@angular/forms";

import {OnInit} from "@angular/core";

export class MyFormComponent implements OnInit {
  doValidation = false;
  form: FormGroup;


  constructor(fb: FormBuilder) {
    this.form = fb.group({
      title: ["", Validators.required]
    });

  }

  ngOnInit() {

  }
  clickSubmitForm() {
    this.doValidation = true;
    if (this.form.valid) {
      console.log(this.form.value);
    };
  }
}

<form class="form-horizontal" [formGroup]="form" >
  <input type="text" class="form-control" formControlName="title">
  <div *ngIf="form.get('title').hasError('required') && doValidation" class="alert alert-danger">
            title is required
        </div>
  <button (click)="clickSubmitForm()">Submit</button>
</form>

于 2016-11-10T14:53:44.410 回答
0

看到这颗宝石。到目前为止,我见过的最优雅的解决方案。

完整代码

import { Injectable } from '@angular/core';
import { FormGroup } from '@angular/forms';

const TOUCHED = 'markAsTouched';
const UNTOUCHED = 'markAsUntouched';
const DIRTY = 'markAsDirty';
const PENDING = 'markAsPending';
const PRISTINE = 'markAsPristine';

const FORM_CONTROL_STATES: Array<string> = [TOUCHED, UNTOUCHED, DIRTY, PENDING, PRISTINE];

@Injectable({
  providedIn: 'root'
})
export class FormStateService {

  markAs (form: FormGroup, state: string): FormGroup {
    if (FORM_CONTROL_STATES.indexOf(state) === -1) {
      return form;
    }

    const controls: Array<string> = Object.keys(form.controls);

    for (const control of controls) {
      form.controls[control][state]();
    }

    return form;
  }

  markAsTouched (form: FormGroup): FormGroup {
    return this.markAs(form, TOUCHED);
  }

  markAsUntouched (form: FormGroup): FormGroup {
    return this.markAs(form, UNTOUCHED);
  }

  markAsDirty (form: FormGroup): FormGroup {
    return this.markAs(form, DIRTY);
  }

  markAsPending (form: FormGroup): FormGroup {
    return this.markAs(form, PENDING);
  }

  markAsPristine (form: FormGroup): FormGroup {
    return this.markAs(form, PRISTINE);
  }
}
于 2019-03-08T11:01:10.657 回答
0

看法:

<button (click)="Submit(yourFormGroup)">Submit</button>   

API

Submit(form: any) {
  if (form.status === 'INVALID') {
      for (let inner in details.controls) {
           details.get(inner).markAsTouched();
       }
       return false; 
     } 
     // as it return false it breaks js execution and return 
于 2019-09-20T09:02:01.700 回答