angularangular-formsform-controlangular-validationdisabled-control

I've to disabled a FormControl but keep validation


I' ve this FormGroup:

this.fb.group({
    a: ["", Validators.required],
    b: ["", Validators.required],
    c: [{value: "", disabled: true}, Validators.required]
});

In template, filling the first 2 control (a and b), generate value for the third one (c) at valueChanges.subscribe() methods.

Below in the form i've a button for next pages. This should be disabled until form is valid (3 controls not empty), but for now it doesn't work as i wish because the third control is disabled and so the validation for that field is skipped. The result is that after the second control is filled, even if my generation function failed and the control "c" remain empty, the button is enabled.

I've seen on other posts the usage of [attr.disabled] but in Angular 15 it doesn't seem to work. Is there another way to disable a field in template keeping validation running?

I'm trying to find a solution different to setting field's error into the generation function.


Solution

  • I think you can reach it by keep the control enabled and just change it's styles by adding/removing next class(if we talk about <input>):

    .disabled-input {
        pointer-events: none;
        cursor: not-allowed;
        // you styles for disabled input, for example:
        opacity: 0.5;
        background-color: #f0f0f0;
        color: #808080;
    }