angularangular-reactive-formsangular-formsangular-validator

How to make a Disabled Input also Required with Angular Reactive Form?


I have an input which will be populated when the user clicks on a dialog. So for this I had to make it disabled, because I don't want the user to manually input the value. The only problem is that this input must be required, and I couldn't make it so far.

I have tried to add 'required' directive in the input and also tried adding Validator.required on the form creation, but none of these made the field required for the form.

createUnityForm(): FormGroup {
    return this._formBuilder.group({
        id      : [this.unity.id],
        description: [this.unity.description],
        floor: [{value: this.unity.floor, disabled: true}, Validators.required]
    });
}

<mat-form-field appearance="outline" floatLabel="always" class="mr-16" fxFlex>
    <mat-label>{{'UNITY.FLOOR' | translate}}</mat-label>
    <input matInput placeholder="{{'UNITY.SELECT-FLOOR' | translate}}"
        name="floor"
        formControlName="floor"
        required>
</mat-form-field>

<button *ngIf="action === 'edit'"
    mat-button
    class="save-button"
    (click)="matDialogRef.close(['save',unityForm])"
    [disabled]="unityForm.invalid"
    aria-label="save">
        {{'GENERAL.SAVE' | translate}}
</button>

unityForm is valid even when there's nothing in the input


Solution

  • If you set a FormControl to disabled its validators will be ignored.

    More info: https://angular.io/api/forms/AbstractControl#disabled