2

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.

2 Answers 2

14

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

Sign up to request clarification or add additional context in comments.

2 Comments

How to set the same value while getting the array of data from database?
Great one, is there a way to show the values on hover of the others instead of clicking the select ?
0

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);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.