Angular Material Toggle Buttons Group with Binding
In this post we are going to create an Angular App to use Button toggle groups from Angular material. We are going to do data binding of these buttons and generate the buttons using a list in the code behind in the component class.
Let’s first create a simple Angular App using Angular CLI.
ng new button-toggle-app
Now let’s install the necessary npm modules to use the toggle buttons.
npm install –save @angular/material @angular/cdk @angular/animations
Let’s import the material modules to app module. This allows them to be used in the whole module.
We need to update styles.css to use angular material theme:
Let’s introduce an array in the code behind (app.components.ts). We are going to use this array to create the list of toggle buttons in UI.
Here we are using the toggleButtons collection with *ngFor. We are binding the individual item to the value property of the toggle button. Please note that we are allowing multiple values to be selected in the button group. We are then displaying the selected options just below the button toggle group.
Default Options & Selected Values
Now let’s introduce the idea of default options when the page is loaded. We can bind value property in the button group to drive this. This can be bound with a string array in the code behind. Here is how we can change the template:
And here is how we can introduce the property in the code behind:
Handling Toggle Event
We can handle toggle events for individual button. We can even pass the selected / unselected value in the button group. It must be remembered that it handles the binding before emitting events so if you want to use the set value of the bound property, it should be alright.
Here is how we can update the code behind. We have just added a method to handle the value change of the buttons. We are just printing the current value and all the values currently selected by the button group.
Now we just need to use it in the template.