Angular change the state of a checkbox after user click

I have the following code that should set the checked value to false on click:

@Component({
  template: `
    <input type="checkbox" [checked]="checked" (change)="onChange()">
   `
})
export class AppComponent  {

  checked = false;

  onChange() {
    setTimeout(() => {
      this.checked = false;
    }, 1000)
  }

}

The problem is that if we click on the input and we wait for a second, it’ll stay checked. Why is this happening? Why Angular doesn’t change it to false again?

10 thoughts on “Angular change the state of a checkbox after user click”

  1. Long story short Angular checkboxes are just broken : Issue

    If you however want to achive this effect i will recommend you to create your own custom component that will act the same way as a checkbox.

    Here is one more fun example of Checkbox madnes try to interact with both "With track by" and "No track by" blocks and see what happens.

    Reply
  2. I think you can do that easily by using [(ngModel)]="checked". Your code is working in the stackblitz link. Please check that. Here is my code given below.

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      template: `
        <input type="checkbox" [checked]="checked" [(ngModel)]="checked" (change)="onChange()"  name="horns">
        <label for="horns">Horns</label>
       `,
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
       checked = false;
    
      onChange() {
        setTimeout(() => {
          this.checked = false;
        }, 2000)
      }
    }
    
    Reply
  3. in angular you can manipulate dom using view child and element ref

    first of all you need to import viewchild and elementRef in your component

    app.component.ts

    import { Component, VERSION } from "@angular/core";    
    import { ViewChild, ElementRef } from "@angular/core";    
    
    @Component({  
    selector: "my-app",  
    templateUrl: "./app.component.html",  
    styleUrls: ["./app.component.css"]  
    })  
    export class AppComponent {  
    @ViewChild("checkBox") el: ElementRef;  
    
    onChange() {    
    setTimeout(() => {  
      this.el.nativeElement.checked = false;  
     }, 100);  
    }  
    }
    

    app.component.html

    <input type="checkbox" #checkBox (click)="onChange()">

    stackblitz

    Reply

Leave a Comment