如何在 MD-selection-list Angular2 中设置选中元素的最大限制

2024-01-18

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

标签存储在this.tags,所选标签存储在this.tab

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

我从这段代码开始,但它不起作用。我尝试禁用列表项上的此“检查”图标,然后在用户存储

这是代码:

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);
}
}

你怎么看待这件事?如何解决这个问题呢?也许还有其他更简单的解决方案?是为了这个问题?

谢谢你的帮助


当选定的计数达到一定限制时,您可以禁用未选定的选项,

<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>

工作示例 https://stackblitz.com/edit/material2-beta12-ehlsjg?file=app/app.component.html

--

更新的示例在选择最终选项时显示警报

EXAMPLE https://stackblitz.com/edit/material2-beta12-txr2qx?file=app%2Fapp.component.ts

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 MD-selection-list Angular2 中设置选中元素的最大限制 的相关文章

随机推荐