在 angular 中显示没有字段模糊的表单错误

Show form error without field blur in angular

在我的应用程序中,我正在尝试 angular validator。如果表单已经填满了数据,那么验证就完美了。但是,如果最初没有填充任何数据,并且如果我单击该按钮,则它不会显示错误。但是,如果我单击某些字段并进行模糊处理,则会显示该字段的错误。

点击按钮时如何显示错误?

validation.service.ts

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

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

  constructor() { }

  static getValidatorErrorMessage(validatorName: string, validatorValue?: any) {
    const config = {
      required: 'validation.required',
      minlength: `Minimum length is ${validatorValue.requiredLength}`,
      email: 'validation.email',
    };
    return config[validatorName];
  }
}

验证-message.component.ts

import { Component, Input } from '@angular/core';
import { FormControl } from '@angular/forms';
import { ValidationService } from '../../services/validation/validation.service';
@Component({
  selector: 'app-errorMessages',
  template: `<div *ngIf="errorMessage !== null">{{errorMessage | translate}}</div>`
})
export class ValidationMessagesComponent {

  @Input() control: FormControl;

  constructor() { }

  /**
   * Function to get the form validation error message
   *
   * @readonly
   * @memberof ValidationMessagesComponent
   */
  get errorMessage() {
    for (const propertyName in this.control.errors) {
      if (this.control.errors.hasOwnProperty(propertyName) && this.control.touched) {
        return ValidationService.getValidatorErrorMessage(propertyName, this.control.errors[propertyName]);
      }
    }
    return null;
  }
}

HTML 显示错误的部分

<app-errorMessages [control]="userForm.controls.userFullName" class="error-msg messages text-left text-danger"></app-errorMessages>

启动提交的按钮

<button type="button" class="btn btn-primary btn-lg btn-block"  ngIf="submitFlag" (click)="onSubmit()">Save</button>

与提交相关的函数

onSubmit(): any {
    // Component points data to the module and module points to the http service
    // use the retun value to trigger a toast Message.
    console.log(this.userForm);
    if (!this.validateUserForm()) {
      console.log('Show errors');
      return false;
    }
    this.userService.createNewUser(this.userForm.value);
  }

validateUserForm() {
    if (this.userForm.invalid) {
      return false;
    }
    return true;
  }

您希望您的条件看起来更像这样:

 if (this.control.errors.hasOwnProperty(propertyName) && (this.control.touched || this.control.submitted)) 

然后您还需要在表单元素中使用 ngSubmit 指令并更改您的按钮类型以提交以使其工作