How do I display errors in a component view with Angular 2?
In Angular 1, the ng-messages modules are used to help us to display error messages and validation to our forms.
In Angular 2, the ngModel provides error objects for each of the built-in input validators. You can access these errors from a reference to the ngModel itself then build useful messaging around them to display to your users.
Example as,
import { Component, Input } from '@angular/core'; import { FormControl } from '@angular/forms'; import { ValidationService } from '../services/validation.service'; //The Component Class. @Component({ selector: 'kg-errorMessages', template: `<div *ngIf="errorMessage !== null">{{errorMessage}}</div>` }) export class ErrorMessagesComponent { @Input() control: FormControl; @Input() name: string; constructor() { } get errorMessage() { for (let propertyName in this.control.errors) { if (this.control.errors.hasOwnProperty(propertyName) && this.control.touched) { return ValidationService.getValidatorErrorMessage(propertyName, this.control.errors[propertyName]); } } return null; } }
//The Validator Services.
export class ValidationService { static getValidatorErrorMessage(validatorName: string, validatorValue?: any) { let config = { 'required': 'Required!', 'invalidNumberField': 'Only numbers allowed!', 'invalidDateField': 'Not a valid date!', 'invalidCreditCard': 'Is invalid credit card number!', 'invalidEmailAddress': 'Invalid email address!', 'invalidPassword': 'Password must be at least 6 characters long, and contain a number!', 'invalidPasswords': 'Invalid passwords. Passwords must match!', 'minlength': `Minimum length ${validatorValue.requiredLength}` }; return config[validatorName]; } static dateFieldValidator(control) { var e: boolean; if (IsValidDate(control.value)) { return null; } else { return { 'invalidDateField': true }; } } static creditCardValidator(control) { // Visa, MasterCard, American Express, Diners Club, Discover, JCB if (control.value.match(/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/)) { return null; } else { return { 'invalidCreditCard': true }; } } static emailValidator(control) { // RFC 2822 compliant regex if (control.value.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/)) { return null; } else { return { 'invalidEmailAddress': true }; } } static passwordValidator(control) { // {6,100} - Assert password is between 6 and 100 characters // (?=.*[0-9]) - Assert a string has at least one number if (control.value.match(/^(?=.*[0-9])[a-zA-Z0-9!@#$%^&*]{6,100}$/)) { return null; } else { return { 'invalidPassword': true }; } } static passwordCompareValidator(fg) { if (fg.value.password === fg.value.confirmPassword) { return null; } else { return { 'invalidPasswords': true }; } } }
References,