如何在角形材质2中选择默认项选择多个 [英] how to select default items in angular material 2 select multiple

查看:57
本文介绍了如何在角形材质2中选择默认项选择多个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用angular 2材质应用程序,在这种情况下,我有一个multiselect元素,并且我有一个带有复选框的列表,因此我可以一次选择多个项目.我能够使用角形材质组件来实现这一点,但是我想要的是默认情况下要检查2-3个项目,并且如果我选择/取消选择了一个特定项目,那么我应该选中/选中标志为true/false.

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.

推荐答案

如果将object绑定到selectoption,则angular将按对象实例比较默认值和选项的值.此处listtest{name: 'abc'}{name:'cbv'}具有相同的字段和值,但它们保留不同的实例.因此,不会将任何内容设置为selected.

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的答案将通过在两个数组上保留相同的对象实例而起作用.

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

另一种解决方案(不需要保持相同的对象实例)是使用 compareWith 指令,请参见

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.

这篇关于如何在角形材质2中选择默认项选择多个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆