undefined
undefined

Reputation: 6884

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?

Upvotes: 5

Views: 3852

Answers (3)

Piyush  Jain
Piyush Jain

Reputation: 323

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

Upvotes: 0

Srijon Chakraborty
Srijon Chakraborty

Reputation: 2164

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)
  }
}

Upvotes: 0

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.

Upvotes: 3

Related Questions