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

How to set maximum limit of checked elements in MD-selection-list Angular2

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

标签存储在this.tags,selected标签存储在this.tab

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

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

这是代码:

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>

WORKING EXAMPLE

--

更新示例,在选择最后一个选项时显示警告

EXAMPLE

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