How to set maximum limit of checked elements in MD

2019-07-26 07:54发布

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

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

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.

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.

This is the code:

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?

Thanks for any help

1条回答
女痞
2楼-- · 2019-07-26 08:29

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>

WORKING EXAMPLE

--

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

EXAMPLE

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.

查看更多
登录 后发表回答