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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With