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

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

问题描述

我正在开发 angular 2 material 应用程序,我有一个案例,其中有多选元素,并且我有一个带复选框的列表,因此我可以一次选择多个项目.我可以使用角度材料组件来做到这一点,但我想要的是默认检查 2-3 个项目,如果我选择/取消选择特定项目,那么我应该将检查/选择标志设置为真/假.

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 会比较对象实例的默认值和选项值.这里 {name: 'abc'}{name:'cbv'}listtest 有相同的文件和值,但它们保持不同的实例.所以没有将设置为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 指令,请参阅 文档.这样你应该实现一个 compareWith 函数来告诉 angular 如何在对象之间进行比较.

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天全站免登陆