0
votes

I'm trying to figure out how to get the selected values of a group of Angular (7) Material checkboxes.

Let's say I have an area on the form "flavors" and 3 checkboxes with values of "chocolate", "vanilla", and "strawberry".

<h3>Flavors</h3>
<mat-checkbox value="chocolate">Chocolate</mat-checkbox>
<mat-checkbox value="vanilla">Vanilla</mat-checkbox>
<mat-checkbox value="strawberry">Strawberry</mat-checkbox>

As the checkboxes are checked on and off, I want to update the variable (model) "flavorsAvailable".

It's simple to do this with mat-radio-groups, since it's just an ngModel on the group element. But how do I manage checkboxes?

Note: I don't want to use an Angular Material Selection list; this is just for forms.

2
What type is flavorsAvailable? What should happen to the model as you check and uncheck your checkboxes? - frido

2 Answers

1
votes

@Steve, a material selecion list you can use [(ngModel)]="variable" [formControl]="control" or in a form, formGroupName="property". In all case you get an array with the selected options. I don't imagine a better way to manage the checkbox.

Well you can use mat-check alone, it's only use [(ngModel)]. e.g. if you has an array of booleans. Yes, has no sense [value] in a mat-check-box, the only allowed values are: true or false

variable:boolean[]=[]

You can use

<mat-checkbox [(ngModel)]="variable[0]" value="chocolate">Chocolate</mat-checkbox>
<mat-checkbox [(ngModel)]="variable[1]" value="vanilla">Vanilla</mat-checkbox>
<mat-checkbox [(ngModel)]="variable[2]" value="strawberry">Strawberry</mat-checkbox>
{{variable|json}}
1
votes

See if this help you:

flavorsAvailable: any[] = [
    { 'id': '0', 'name': 'chocolate' },
    { 'id': '1', 'name': 'vanilla' }
];

getCheckeds(ev): any[] {
  return this.flavorsAvailable.filter(x => x.state = ev.target.checked);
}

If this is the type of list that you did mention on "I don't want to use an Angular Material Selection list; this is just for forms.". Them, this don't make sense, you would need to pick one by one in 3 different ngModels...