Reputation: 957
Is it possible to change displayed value in Angular Material multiple select? How can I do this e.g. Products:(0/12) depends on number of selected items.
Upvotes: 2
Views: 9675
Reputation: 76
In addition to the answer above, to set the selection to an initial value, this is how you'd extend select-custom-trigger-example.ts
in the given stackblitz demo:
import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
/** @title Select with custom trigger text */
@Component({
selector: 'select-custom-trigger-example',
templateUrl: 'select-custom-trigger-example.html',
styleUrls: ['select-custom-trigger-example.css'],
})
export class SelectCustomTriggerExample implements OnInit {
toppings = new FormControl();
toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];
ngOnInit()
{
// initalSelection could be the result from a service call (database, backend, etc.):
let initalSelection : string [] = ["Onion","Pepperoni","Sausage"];
// set initalSelection as inital value:
this.toppings.setValue(initalSelection);
}
}
Upvotes: 0
Reputation: 17908
Use a <mat-select-trigger>
for that. For example:
<mat-form-field>
<mat-select placeholder="Toppings" [formControl]="toppings" multiple>
<mat-select-trigger>
{{toppings.value ? toppings.value[0] : ''}}
<span *ngIf="toppings.value?.length > 1" class="example-additional-selection">
(+{{toppings.value.length - 1}} {{toppings.value?.length === 2 ? 'other' : 'others'}})
</span>
</mat-select-trigger>
<mat-option *ngFor="let topping of toppingList" [value]="topping">{{topping}}</mat-option>
</mat-select>
</mat-form-field>
See the demo here: https://stackblitz.com/angular/qkjbojyxebly?file=app%2Fselect-custom-trigger-example.html
Upvotes: 14