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

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published