Can't push selected items in array – Angular material mat select multiple

Issue

Could someone help me to identify where im doing wrong when pushing data to empty array?

So, Am trying to push only selected values (i.e only checked true). but i cant go inside the loop

condition i had now

const vals = [];
    if (e && e.source.selected.length > 0) {
      console.log('selected values', e.source.selected);
      const sel = e.source.selected;
      sel.forEach((e: any) => {
        if (sel._selected) {
          vals.push(e);
          console.log('EE', e);
        }
      });
    }

demo blitz

expected:

selectedList : [
{ id: '0' }, { id: '1' }, { id: '2' }
]

Purpose:

trying to bind same data in edit mode in form

Solution

You don’t need your function at all. Remove it completely and instead do

console.log(e.source.value);

It automatically contains all selected values !

Each time you make an update the array will be updated as well to contain only the selected values.

If you want to transform it

expected:

selectedList : [ { id: ‘0’ }, { id: ‘1’ }, { id: ‘2’ } ]

then just do

let selectedList = e.source.value.map((elem: number) => ({ id: elem }));
console.log(selectedList);

Answered By – Panagiotis Bougioukos

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.