Jendrik
Jendrik

Reputation: 270

Angular - How to set selected values for a mat-select from a datasource of a dynamic sized table

I am setting up a mat-table that shows some values from a datasource and has a mat-select with multiple select in each row. The datasource for the table is an array of objects("CarManufacturer"), that holds another array of objects("Brand"). In the mat-select I show a complete list of all "Brands".

At the moment I cant de-/select those "Brands". They are marked as selected or not. I am not able to change this.

I have created a function that returns an array of number(ids of brands), which feeds [value] of mat-select. That marks brands in the dropdown which are in the array of CarManufactors, but I cannot select anything in the dropdown.

Code: https://stackblitz.com/edit/angular-skrrhb

I expect that I can change the values of the dropdown. At the moment I cannot de-/select the values.

Upvotes: 1

Views: 7532

Answers (1)

Daniel Piñeiro
Daniel Piñeiro

Reputation: 3149

The problem is that <mat-select [value]="getArray(element.brands)" multiple> is always returning the same value no matter what.

One solution would be to add an brandSelected in the brand interface and store the values there:

export interface CarManufacturer {
  id: number;
  name: string;
  brands: Brand[];
  brandsSelected?: number[]; 
}

And then apply a two way data binding in the mat-select like this:

   <mat-select [(value)]="element.brandSelected" multiple>

You can see the working example here:

https://stackblitz.com/edit/angular-ujirgb?file=src%2Fapp%2Fapp.component.html

Upvotes: 3

Related Questions