如何在 MD-selection-list Angular2 中设置选中元素的最大限制 [英] How to set maximum limit of checked elements in MD-selection-list Angular2

查看:15
本文介绍了如何在 MD-selection-list Angular2 中设置选中元素的最大限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 md-selection-list 和一些标签的 *ngFor,例如 [sport,relax,..]

i have md-selection-list with *ngFor of some tags, for example [sport,relax,..]

标签存放在this.tags,选中标签存放在this.tab

The tags are stored in this.tags, and the selected tags are stored in this.tab

我想阻止用户选择超过 5 个标签.所以如果用户选择第 5 个项目,应该有一些警告,并且用户只有在取消选中某些已选中的项目时才能键入不同的标签.

I want to prevent user for selecting more than 5 tags. So if user select 5th item, there should be some alert, and user can type different tag only when unchecked some of checked items.

我从这段代码开始,但它不起作用.我尝试在列表项上禁用此检查"图标,然后在用户存储 <5 个标签之前不将该项目添加到 this.tab.问题是我无法禁用这个检查"图标.

I start with this code, but it isn't working. I try to disable this "check" icon on list-item, and then not add the item to this.tab until the user have <5 tags stored. The problem is I can't disable this "check" icon.

这是代码:

clickedOnRow(row){

if(this.tab.length > 5){

  this.tags.forEach((item,index) =>{
    if(item.text == row.text){

      this.selectedList.nativeElement.children[index].children[0].children[1].classList.remove('mat-pseudo-checkbox-checked')
      this.selectedList.nativeElement.children[index].children[0].children[1].className = 'mat-pseudo-checkbox'
    }
  });

}else{
  this.tab.push(row.text);
}
}

你怎么看这件事?如何解决这个问题呢?也许其他一些解决方案,更容易?是为了这个问题?

What do You think about this? How to solve this problem? Maybe some other solution, easier? is for this problem?

感谢您的帮助

推荐答案

当所选计数达到某个限制时,可以禁用未选择的选项,

You can disable unselected options when the selected count reaches some limit,

<mat-selection-list #shoes>
  <mat-list-option
      #shoe
      *ngFor="let shoeType of typesOfShoes"
      [disabled]="shoes.selectedOptions.selected.length > 2 && !shoe.selected">
    {{shoeType}}
  </mat-list-option>
</mat-selection-list>

工作示例

--

更新了在选择最后一个选项时显示警报的示例

Updated example that shows an alert when the final option is selected

示例

老实说,我对此很懒惰,可能有更好的方法,但它有效.选择列表还有一个改进的 selectionChange 事件,将在下一个版本中引入.我认为,点击处理程序是您现在可以做的最好的事情.

To be honest, I was lazy about this and there are likely better ways, but it works. Also selection list has an improved selectionChange event that will be introduced in the next release. A click handler is the best you can do right now, I think.

这篇关于如何在 MD-selection-list Angular2 中设置选中元素的最大限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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