5

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?

1
  • Please check my answer and let me know does it worked for you or not. Best wishes :-) Commented Feb 18, 2021 at 10:33

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

@undefined I apologized for my callowness to explain why [checked]="checked" is not working. Actually, every single time I have used ngModel to display and manipulate data. It works almost like real-time. :-(
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.