57

I have a angular element

<mat-checkbox class="btn-block" 
              labelPosition="before" 
              (change)="showOptions($event)" 
              (click)="makeJSON($event.checked,i,j,k)">
</mat-checkbox>

Here onchange(which actually gives the status of checkout) is doing some other task and I want the status of checkbox(either checked or unchecked) on click event.

I already tried looking over the object created by click and it does not have click object inside, so how can I detect if the checkbox is checked or not.

Jnr
  • 1,504
  • 2
  • 21
  • 36
Apoorv
  • 1,338
  • 1
  • 17
  • 18
  • @Apoorv did Gunter's answer solve your problem? If so, please accept it. If not, please edit your question to state why you don't feel that it solves your problem. An important part of using this site is to accept answers that solves your problem. The reason for this is twofold: 1) it tells us that your question is resolved and doesn't require further answers. 2) it helps future readers with the same question be directed to a useful answer. – ProgrammingLlama May 27 '19 at 06:02

5 Answers5

79

You can use

(change)="showOptions($event)" 
(change)="makeJSON($event.checked,i,j,k)">

or

(change)="showOptions($event);makeJSON($event.checked,i,j,k)">
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
39

With your (change)="showOptions($event)" you can simply get the status like this:

showOptions(event:MatCheckboxChange): void {
    console.log(event.checked);
}
Jnr
  • 1,504
  • 2
  • 21
  • 36
15

Another solution can be, You can use template reference variable with checkbox and pass that variable to method parameter.

 <mat-checkbox #checkbox (change)='showOptions(checkbox.checked)' value=''>all</mat-checkbox> 

Here #checkbox reference hold all checkbox related properties(like value, checked etc.). checkbox.checked this will give current state of checkbox with true and false.

sharad jain
  • 1,471
  • 13
  • 9
8

Yes you can get the checked event using change function (change)="showOptions($event);

In Ts

showOptions(event){
 console.log(event.checked); //true or false
}

When Checkbox is false not checkedenter image description here

When Checkbox is true then its checked enter image description here

VIKAS KOHLI
  • 8,164
  • 4
  • 50
  • 61
4
whTax =false;                  
<mat-checkbox color="primary"
                      name="whTax" [checked]="false"
                      [(ngModel)]="whTax" id="IsHold"
                      (change)="onWHChange(whTax)">
                        W/H TAX
                  </mat-checkbox>
    onWHChange(isWhChecked){
      console.log('isWhChecked:>>', isWhChecked);
    }
Pavan Raju
  • 51
  • 1