0
votes

I'm trying to create a wrapper component for material button-toggle-group. I should add a lot of custom styling for it, so it makes sense to do this in a component so I can import this component later rather than doing it every time. However, I've hit a snag. It is only possible to click the button one time, and then it is checked forever. Also, all buttons can be checked at the same time. What I'm wondering is:

  • How do I change the selected button when option is selected?
  • How can I use the boolean in the dataset to set one of the buttons to checked by default?
  • Also, how can I limit it to one selection at a time? I tried setting the "multiple"-parameter to false, but this does not seem to work.

I have provided what I have so far in a Stackblitz - for some reason this is not loading the material theme properly, but you can still see the problem and what I have so far: https://stackblitz.com/edit/angular-b7rxxq

1

1 Answers

1
votes

A mat-button-toggle-group is intended to be a group of several buttons... because your loop is on the mat-button-toggle-group you are creating two groups each containing one button.

Remove your loop from mat-button-toggle-group

<mat-button-toggle-group (change)="optionSelected($event)" multiple="false" [name]="label">

Add it to the mat-button-toggle so you have a yes and no in one mat-button-toggle-group... also use [checked]="option.value to default the value

<mat-button-toggle i18n="{{option.i18n}}" [value]="option.value" [checked]="option.value" *ngFor="let option of options" style="margin-left:15%">{{option.displayValue}}</mat-button-toggle>

Please Note: once your options are in a single group, only one will ever be selected at a time... once selected you cannot deselect... you will need to do it programmatically if you need the ability to deselect.

Stackblitz

https://stackblitz.com/edit/angular-rmn4k4?embed=1&file=src/app/toggle-wrapper/toggle-wrapper.component.html