Показать ошибку формы без размытия поля в угловых

В моем приложении я пытаюсь 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;
  }

1 ответ

Решение

Вы хотите, чтобы ваше условное выражение выглядело так:

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

Затем вам также нужно использовать директиву ngSubmit в элементе формы и изменить тип кнопки, чтобы она работала.

Другие вопросы по тегам