Home > database >  How to conditionally set a [disabled] attribute value in an Angular Reactive Form?
How to conditionally set a [disabled] attribute value in an Angular Reactive Form?

Time:05-26

In an Angular reactive form, we have a checkbox which is required to be checked before our save button will work. Now, we have a new requirement to only display this checkbox to certain regions, which is easily accomplished via an environment property and an *ngIf on the checkbox.

However, how do I conditionally make that save button's [disabled] attribute not care about the checkbox?

my-component.component.html

      <div *ngIf="isMyCheckboxRegion">
        <input [formControl]="myCheckbox" type="checkbox" id="my-checkbox">
        <label for="my-checkbox">Please check this box</label>
      </div>

      <div>
        <button validationgroup="SaveMyForm"
          (click)="onSubmit()" [disabled]="anotherFormGroup.invalid || myCheckbox.invalid">Save</button>
      </div>

my-component.component.ts

import { environment } from 'src/environments/environment';

    export class myComponent implements OnInit {
        public isMyCheckboxRegion = environment.isMyCheckboxRegion;
        public myCheckbox = FormControl('', Validators.requiredTrue);
    }

CodePudding user response:

Try setting Validators.requiredTrue conditionally:

public myCheckbox = FormControl('', this.isMyCheckboxRegion ? Validators.requiredTrue : undefined);

As the validator is applied conditionally, myCheckbox.invalid should be false regardless of the checkbox's value.


Alternative:

You can also use isMyCheckboxRegion in the HTML:

<button 
 validationgroup="SaveMyForm"
 (click)="onSubmit()" 
 [disabled]="anotherFormGroup.invalid || (isMyCheckboxRegion && myCheckbox.invalid)"
>Save</button>
  • Related