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

98
Visualizações
Uncheck checkbox in Angular 2 ngModelChange event

We have a form in an Angular 2 app. The form has a checkbox. Under some circumstances, checking the checkbox is illegal. When the user checks the checkbox, we want to show an error message and uncheck the checkbox.

This almost works. In our event handler we check the condition, warn the user and set the checkbox variable back to false. Unfortunately, the checkbox remains checked.

The order of events as we have seen it is this:

  1. User clicks the checkbox.
  2. Our checkbox variable becomes true.
  3. Our event handler is called.
  4. Alert is shown (using alert for now)
  5. Alert is dismissed
  6. checkbox variable set to false by our code.
  7. Our event handler finished.
  8. Checkbox is checked in the browser

    The model (checkbox) remains false, but the user doesn't see it. How can I uncheck the checkbox after it is actually checked (as opposed to 'about-to-be-checked')?

    Here is a Plunkr demonstrating the issue.

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Original answer :

Wrap your this.checkbox=falsewith a setTimeout :

@Component({
  selector: 'my-app',
  template: `
    <label>
        <input type='checkbox' [(ngModel)]='checkbox' (ngModelChange)='onCheckboxChange()'>    Can't be checked
    </label>
    <pre>{{checkbox}}</pre>
  `,
})
export class App {
  name:string;
  checkbox: boolean;
  constructor() {
    this.checkbox = false;
  }
  
  onCheckboxChange() {
    if (this.checkbox) {
      setTimeout(()=>{
        this.checkbox = false;
      })
    }
  }
}

plunkr

For future readers :

You can find explainations about why this setTimeoutmight be required on this question :

Angular 2 - Checkbox not kept in sync

about 4 years ago · Santiago Trujillo Relatório

0

you need to share some code ,but as per description problems seems to be with ngModel to unchecked the checkbox use like this

<input type="checkbox" [checked]="your condition">
about 4 years ago · Santiago Trujillo 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