问题
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:
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.
来源:https://stackoverflow.com/questions/46768773/how-to-set-maximum-limit-of-checked-elements-in-md-selection-list-angular2