Angular 5 Material Design — Checkbox array Reactive forms handle

Gregory Kaidanov
2 min readMay 30, 2018

--

Two solutions for checkbox array

Simple Checkbox array and Selection list array

If we are going for the simple option it looks a bit plain. Of course we always can play with the css and general design.. But overall the Selection List was quicker and easier for me at the end.

mat-checkbox array handle

  1. We are initiating the data from service
  2. Define the form to get array in the future to come
  3. Define the html to create the controls of the checkboxes by the data received
  4. Connect the data to the form by the formArrayName — that’s the glue of the general angular 5 scope to the form builder scope.
  5. Add the ability to change the data by searching and updtaing data when changed.

P.s.

So in the html we are setting an array of check-boxes , it can work with simple html no Material Design controls as well.

On the change event we are updating the values , by finding the correlating FormArray by the key we are sending in. So actually, we can use multiple check-boxes arrays in one component.

Very simple code — you can find it bellow.

You are welcome to propose improvements.

Cheers!

mat-selection-list simple sample

So here it’s almost the same just looks a bit nicer and I’ve developed it very quick.. also it was after the first example so it was easier..

In this case the revert was very easy , just nullified the arrays of the selected items.

The change here was -

The connection to the values was made through built in mechanism of [(ngModel)]=”selectedNotifications” , hence not needed to be updated or handled by me in any way.

At the end I run through the form, nullify existing values and set the new set of the values from the current state of the form. To tell the truth at this point the code can be a bit optimized.

Another trick I used was unifying the id and value of the checkbox into the value property . It helped me to use the selectedNotifications as the only source of data to re-analyze by simple string manipulation and init the Control Forms without corresponding to the initial data.

Enjoy.

You are welcome to follow me here and share my posts..
On my tech facebook page — my black notebook for usefull links I use and like — https://www.facebook.com/set4u.biz/

There is no stupid questions..

--

--