Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

453
Visualizações
How to conditionally set a [disabled] attribute value in an Angular Reactive Form?

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);
    }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda