Search code examples
javascriptangulartypescriptangular4-forms

Angular 4 disabled FormControl does not check or show validating errors


I have FormControl object bind to input element.

<input matInput [formControl]="nameControl">

It is initialized as follows

this.nameControl = new FormControl({value: initValue, disabled: true}, [Validators.required, UniqueValueValidator(uniqueValues)]);

When FormControl is disabled, it does not check for any errors.

Question is how do I keep the control disabled and still show the errors.


Solution

  • It is impossible to get valid or invalid status when form control is disabled.

    A form control have four types of status: pending, disabled, valid and invalid, and will only keep one of these status. So when form control's status is disabled, it will only be disable, not valid, neither invalid, see docs.


    Technically you can simulate the validating process but anything based on input.hasError('...') or invalid/valid won't work.

    <input matInput [formControl]="nameControl">
    <div *ngIf="form.get('nameControl').disabled && form.get('nameControl').value === ''">
      field is required.
    </div>