如何在MD选择列表Angular2中设置检查元素的最大限制

Mac*_*cik 1 angular-material angular2-forms angular

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

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

我想防止用户选择5个以上的标签。因此,如果用户选择第5个项目,则应该有一些警报,并且仅当未选中某些已选中项目时,用户才能键入其他标签。

我从这段代码开始,但是没有用。我尝试禁用列表项上的“检查”图标,然后在用户存储了<5个标签之前,不要将其添加到this.tab。问题是我无法禁用此“检查”图标。

这是代码:

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);
}
}
Run Code Online (Sandbox Code Playgroud)

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

谢谢你的帮助

Wil*_*ell 6

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

<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>
Run Code Online (Sandbox Code Playgroud)

工作实例

-

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

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