How to get the value from angular material checkbox

Viewed 60071

I have a list of checkboxes:

    <section *ngFor="let item of list">
      <mat-checkbox [checked]="item.value" (click)="toggle(_checkbox_value_here_)">{{item.key}}</mat-checkbox>
    </section>

I need to pass the checkbox value (_checkbox_value_here_) to my function, how would you do that?

I can see this related question How to get checkbox data in angular material but really is there a way go achieve that without using ngModel and reactive forms?

7 Answers

The click event on the checkbox is just the native click event, which doesn't know anything about the checkbox itself. Using the change event or just getting a handle on the MatCheckbox instance directly (e.g. with @ViewChildren) would be the recommended approach.

(c) https://github.com/angular/material2/issues/13156#issuecomment-427193381

<section *ngFor="let item of list">
  <mat-checkbox [checked]="item.value" (change)="toggle($event)">{{item.key}}</mat-checkbox>
</section>

you may use the element's checked property.

<mat-checkbox #c (click)="toggle(!c.checked)">Check me!</mat-checkbox>
  • notice it's !c.checked, because by the time you click it, it's not checked yet.

Stackblitz Demo

You can use the approach mentioned by Kuncevič. To get the exact value you want to use something like this

<section *ngFor="let item of list">
  <mat-checkbox [checked]="item.value" (click)="toggle($event)">{{item.key}}</mat-checkbox>
</section>

And in the typescript use "event.source" to retrieve the value

toggle(event){
  console.log(event.source.value);
}

I solved it this way:

HTML:

<mat-checkbox class="chklist" labelPosition="after" (change)="seleccionRubros($event)">

TS:

public seleccionRubros(event: MatCheckboxChange) {

   if (!event.source.checked) {
      this.subRubrosSelec = [];
   }

};

Notice how I passed $event inside seleccionRubros() in the (change) event, and later on determined that on click, the checkbox was either checked or unchecked by reading event.source.checked.

As a clarification, I decided to specify the type of event but it's not actually needed.

Pass $event to the function

<section *ngFor="let item of list">
  <mat-checkbox [checked]="item.value" (click)="toggle($event)">{{item.key}}</mat-checkbox>
</section>

You can get value in function from event object..

toggle(event){
  console.log(event)
}

I think it will be event.value (not sure on this. You can see in console)

Related