Issue
I want to let a user input only one chip in mat-chip with auto complete. I know md-chips has md-max-chips to set maximum number of chips. but I am using mat-chip and how can I set maximum number of chips like this?
<mat-chip-list maxLength="1">
:
:
</mat-chip-list>
Solution
You can't set it directly on the MatChipList
as far as I know. What you could do is, check the number of selected chips yourself for each chip the user is trying to add and then decide whether to add the chip or not, based on the number of chips already added.
Check out this stackblitz taken from the official documentation and modified to solve your problem.
All I changed was this (when adding chips via auto-complete):
selected(event: MatAutocompleteSelectedEvent): void {
if (this.fruits.length < 1) { // <-- THIS
this.fruits.push(event.option.viewValue);
this.fruitInput.nativeElement.value = '';
this.fruitCtrl.setValue(null);
}
}
And this (when adding chips via typing):
add(event: MatChipInputEvent): void {
// Add fruit only when MatAutocomplete is not open
// To make sure this does not conflict with OptionSelected Event
if (!this.matAutocomplete.isOpen) {
const input = event.input;
const value = event.value;
// Add our fruit
if ((value || '').trim() && this.fruits.length < 1) { // <-- THIS
this.fruits.push(value.trim());
}
// Reset the input value
if (input) {
input.value = '';
}
this.fruitCtrl.setValue(null);
}
}
Basically you check the number of chips already selected, before you add any new chips. Edit your code accordingly, the above examples should cover both cases (auto-complete and typing).
Answered By - Fabian Küng
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.