简体   繁体   中英

Checkbox checked state in Angular 10

I am using Angular 10. I have a checkbox in my html file. In my typescript file I want to see if the checkbox is checked or not and perform some action accordingly. Is there a way to get the checked state of the checkbox like true if it is checked and false otherwise? TIA.

To my knowledge, we have two ways of checking the state of the checkbox:

  1. Use the library for angular, Ex: Material UI: https://material.angular.io/components/checkbox/examples or different libraries.
  2. Use two-way binding of angular [(ngModel)] ="checked" on the HTML template

you can use two-way binding like this

html

<input type="checkbox" [(ngModel)]="checked">

ts

checked = false;

You can use change event to check the state

<input type="checkbox" (change)="onSelect($event.target.checked)">


onSelect(state:boolean) {
     console.log("Is Checked? ", state)
}

If you are not using Template Form or Reactive Form,

<input type="checkbox" (change)="changeEvent($event.target.checked)">

For Template Forms,

<input type="checkbox" [(ngModel)]='checked' (ngModelChange)="changeEvent()">

For reactive forms,

<input type="checkbox" formControlName='check'>

this.form.get('check').valueChanges
.subscribe((check)=> this.changeEvent())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM