Reputation: 209
I have the following 3 input checkboxes, after checking the checkboxes, I would like to clear all the checked items after the "Clear Checkbox" button is clicked. I attempted the following but it doesn't work.
app.component.html
<ul *ngFor="let d of data">
<li>
<input id="checkbox" type="checkbox" class="checkbox" />
{{ d }}
</li>
</ul>
<button (click)="myFunction()">Clear Checkbox</button>
app.component.ts
export class AppComponent {
data = ['tea', 'coffe', 'soda'];
public myFunction() {
(<HTMLInputElement>document.getElementById('checkbox')).checked === false;
}
}
Upvotes: 1
Views: 4199
Reputation: 73337
I would do it in an angular fashion and use ViewChildren
instead. So attach a ref to your checkboxes and access them with ViewChildren
, as this would be a perfect case for that. So I attached chkboxes
to the input
<input #chkboxes id="checkbox" type="checkbox" class="checkbox" />
I define the querylist:
@ViewChildren('chkboxes') chkboxes: QueryList<ElementRef>;
and to uncheck I loop the elements and set them to false:
myFunction() {
this.chkboxes.forEach(x => x.nativeElement.checked = false)
}
Upvotes: 3
Reputation: 4587
You can use document.querySelectorAll()
to uncheck all the checkboxes.
In myFunction
, you code should be as below:
document.querySelectorAll('.checkbox').forEach(_checkbox=>{
(<HTMLInputElement>_checkbox).checked = false;
});
Also, make sure you are assinging false
value (=) not checking (===)!
Upvotes: 4