Best way to show error messages for angular reactive forms, one formcontrol multiple validation errors?

前端 未结 5 1344
春和景丽
春和景丽 2021-02-06 08:56

I am showing reactive form error messages as per the suggested approach of angular angular form validation error example.

html code of showing error on the page

5条回答
  •  执念已碎
    2021-02-06 09:43

    A better way to handle all the error, Create a separate component error-component

    error.component.ts

    import { Component, Input } from '@angular/core';
    import { AbstractControl, AbstractControlDirective } from '@angular/forms';
    
    @Component({
        selector: 'error-component',
        templateUrl: 'error.component.html',
        styleUrls: ['error.component.scss']
    })
    
    export class ErrorComponent {
    
        errorMsgList: any = [];
    
        @Input() controlName: AbstractControl | AbstractControlDirective
    
        errorMessage = {
            'required'  : (params)  => `This field is required`,
            'maxlength' : (params)  => `Maximum ${params.requiredLength} characters are allowed`,
            'minlength' : (params)  => `Minimum ${params.requiredLength} characters are required`,
            'pattern'   : (params)  => `Invalid format`,
            'min'       : (params)  => `Minimum amount should be ₹ ${params.min}`,
            'whitespace': (params)   => `White spaces are not allowed`
        };
    
    
        listErrors() {
            if (!this.controlName) return [];
            if (this.controlName.errors) {
                this.errorMsgList = [];
                Object.keys(this.controlName.errors).map( error => {
                    this.controlName.touched || this.controlName.dirty ?
                    this.errorMsgList.push(this.errorMessage[error](this.controlName.errors[error])) : '';
                });
                return this.errorMsgList;
            }
            else {
                return [];
            }
        }
    }
    

    error.component.html

    
        {{last ? errorMessage: ''}}
      
    

    Usages

    
       
        
    

提交回复
热议问题