Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get checkbox value in angular?

can you please tell me a way to get checkbox value in angular 2

here is my code

https://stackblitz.com/edit/angular-grtvc7?file=src%2Fapp%2Fapp.module.ts

one way I know how to do that using the template variable like this

<mat-checkbox #ch>Check me!</mat-checkbox>

  checkCheckBoxvalue(ele){
    console.log(ele.checked)
  }

I want to know another way to achieve this functionality

like image 588
naveen Avatar asked Jun 20 '18 10:06

naveen


1 Answers

you need to use change event

<mat-checkbox (change)="checkCheckBoxvalue($event)">Check me!</mat-checkbox>

checkCheckBoxvalue(event){
    console.log(event.checked)
  }

Working Example

other ways -

  • You can use two way data binding for the same like mentioned below -

    <input type="checkbox" name="myData" [(ngModel)]="isChecked">
    
  • You can use a local variable as well and fetch the value in controller side like below -

    <input type="checkbox" name="myData" #myCheckbox>
    
    @ViewChild('myCheckbox') myCheckbox;
    console.log(myCheckbox, 'Value of checkbox');
    
  • Other way is you can use formControl for the same, either it can be model-driven form or template-driven form.

like image 122
Pardeep Jain Avatar answered Oct 14 '22 03:10

Pardeep Jain