How to create a component to display error messages throughout the application?

1.1K    Asked by RachelKerr in Python , Asked on Jan 19, 2020
Answered by Arun Singh

We can move the validation errors into a component and pass in the formControl.errors as an input property. That way all the validation messages can be reused.

validation-errors.component.ts

import { Component, OnInit, Input, ChangeDetectionStrategy } from '@angular/core';

import { FormGroup, ValidationErrors } from '@angular/forms';

@Component({

  selector: 'validation-errors',

  templateUrl: './validation-errors.component.html',

  styleUrls: ['./validation-errors.component.css'],

  changeDetection: ChangeDetectionStrategy.OnPush

})

export class ValidationErrorsComponent implements OnInit {

  @Input() errors: ValidationErrors;

  constructor() {}

  ngOnInit() {}

}

validation-errors.component.html

Required

Already exists

Please enter a valid email

For the back validation messages set the error manually on the form control.

const nameControl = this.userForm.get('name');

nameControl.setErrors({

  "notUnique": true

});

To use the validation component on the form:


   

     

     

       

     

   

   

     

     

       

     

   

   

 




Your Answer

Interviews

Parent Categories