Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value from angular material checkbox

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?

like image 965
sreginogemoh Avatar asked Nov 13 '18 13:11

sreginogemoh


People also ask

How do you checked the checkbox in angular?

AngularJS ng-checked DirectiveThe ng-checked directive sets the checked attribute of a checkbox or a radiobutton. The checkbox, or radiobutton, will be checked if the expression inside the ng-checked attribute returns true. The ng-checked directive is necessary to be able to shift the value between true and false .

How check checkbox is checked or not in angular material?

Angular Material can be checked dynamically using checked property of <mat-checkbox> element. Checkbox can also be checked using Angular ngModel . The ngModel can be used for two-way binding. Angular Material <mat-checkbox> has change event that is emitted when checkbox is checked and unchecked.

How check if checkbox is checked?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

How do you make a checkbox readonly in angular 8?

How do I make a checkbox readonly in AngularJS? AngularJS ng-readonly Directive The ng-readonly directive sets the readonly attribute of a form field (input or textarea). The form field will be readonly if the expression inside the ng-readonly attribute returns true.


2 Answers

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

like image 151
Stavm Avatar answered Sep 23 '22 10:09

Stavm


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>
like image 30
angularrocks.com Avatar answered Sep 23 '22 10:09

angularrocks.com