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

前端 未结 5 1346
春和景丽
春和景丽 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:48

    I've been working on an enterprise application that is primary form driven and ran into the same challenge. The best solution I could determine was wrapping all of my input controls in components. Then handling the validation display within the component. This allows consistent validation display without repeating the code multiple times in each form.

    field-input-text.component.html

        
        
            This field is required
            This field is too short
            This field is too long
            Invalid value for this field
        
    

    field-input-text-component.ts

        import { Component, OnInit } from '@angular/core';
        import { FormControl } from '@angular/forms';
    
        @Component({
          selector: 'app-field-input-text',
          templateUrl: './field-input-text.component.html'
        })
        export class FieldInputTextComponent implements OnInit, AfterViewInit {
          @Input() formControlItem: FormControl;
          @Input() maxlength: number;
          @Input() placeholder: string = '';
    
          constructor() { }
    
          ngOnInit() {
          }
        }
    

    Usage

        
    

    In the usage, you can see the space it saves without needing the extra validation lines. You can also reformat all of the validation in one place instead of touching every area.

    The main disadvantage is not being able to use the formControl or formControlName attributes. I tried creating a custom ControlValueAccessor component but that did not help with the validation display.

    I found your question searching to see if anyone else have found a better way. I know this answer is a little late but hopefully it helps.

提交回复
热议问题