angular – Reactive Forms – 将字段标记为已触摸

前端之家收集整理的这篇文章主要介绍了angular – Reactive Forms – 将字段标记为已触摸前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我无法找到如何将所有表单的字段标记为触摸.
主要问题是,如果我不触摸字段并尝试提交表单 – 验证错误显示.我的控制器中有一段代码占位符.
我的想法很简单:

>用户点击提交按钮
>所有字段标记为触及
>错误格式化程序重新运行并显示验证错误

如果有人知道如何在提交时显示错误,而不实施新方法 – 请分享.谢谢!

我的简化形式:

<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] + ' ';
        }
      }
    }
  }
}
以下函数通过表单组中的控件进行递归并轻轻触摸它们.因为controls字段是一个对象,所以代码在表单组的控制字段上调用Object.values().
/**
   * Marks all controls in a form group as touched
   * @param formGroup - The group to caress..hah
   */
  private markFormGroupTouched(formGroup: FormGroup) {
    (<any>Object).values(formGroup.controls).forEach(control => {
      control.markAsTouched();

      if (control.controls) {
        control.controls.forEach(c => this.markFormGroupTouched(c));
      }
    });
  }
原文链接:https://www.f2er.com/angularjs/143939.html

猜你在找的Angularjs相关文章