Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to select default items in angular material 2 select multiple

I'm working on angular 2 material app, I have a case where there is multiselect element and in that I have a list with checkbox so I can select multiple items at a time. I'm able to to that with angular material component, but what I want is 2-3 items to be checked by default, and if I select/deselect a particular item, then I should get checked/selected flag as true/false.

<md-select multiple="true" [(mgModel)]="test">
  <md-option *ngFor="let l of list" [value]="l">
    {{l.name}}
  </md-option>
</md-select>

var list = [{name:'abc'},{name:'cbv'},{name:'hgf'},{name:'rty'},{name:'fdv'},{name:'vbg'}]

var test = [{{name:'abc'},{name:'cbv'}]

Is there some other way around or m going wrong some where.

like image 982
Rohan Sampat Avatar asked Dec 13 '22 20:12

Rohan Sampat


1 Answers

If you bind object to option of select, angular will compare default value and option's value by object instance. Here {name: 'abc'} and {name:'cbv'} of list and test have the same filed and value, but they keep different instance. So none will be setted to selected.

@yurzui's answer will work by keeping same object instance at both arrays.

Another solution(which you don't need to keep the same instance of object) is using compareWith directive, see docs. This way you should implement a compareWith Function to tell angular how to compare between objects.

<md-select multiple="true" [(ngModel)]="test" [compareWith]="compareWithFunc">
  <md-option *ngFor="let l of list" [value]="l">
    {{l.name}}
  </md-option>
</md-select>

compareWithFunc(a, b) {
  return a.name === b.name;
}

see demo.

like image 73
Pengyy Avatar answered May 12 '23 02:05

Pengyy