Search code examples
angularvalidationinputangular-material

How to create custom input component with validation using angular material inputin Angular14?


I want to create custom component for input text using angular material input but I don't know how can I bind validation of each input field to custom component. Is there any way to set errors of each field as array of objects like below

<app-custom-input
          formControlName="username"
          label="Username"
        ]"
        ></app-custom-input>

I want the validation to be set into formControl into my formGroup similar to this

 form: FormGroup;
  constructor(
    private fb: FormBuilder
  ) {
    this.form = new FormGroup({
      name: new FormControl('', Validators.required)
    });

https://stackblitz.com


Solution

  • You will have to write a component which implements the ControlValueAccessor interface.

    Inside it, you will have a "standard" AbstractControl (i.e. FormGroup, FormControl, FormArray) instantiated like a normal one (i.e. control = this.fb.control(null, Validators.required);)

    Here you can find a good starting point.