how to select default items in angular material 2 select multiple

我的未来我决定 提交于 2019-12-04 12:13:07

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.

Your test array should contain elements from list array:

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

test = this.list.slice(0,2);

Plunker Example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!