javascriptangulartypescriptangular-materialmat-select

Angular Material - Display different text in dropdown view instead of options selected


I have a multi-select dropdown where there's a option as "ALL" which selects all the options in the list. My requirement is when "ALL" is selected or user manually selects all the option, then in the view "ALL" should show instead of the options selected and the value in the FormControl will also get set as ALL else whatever the user had selected.

This is the Stackblitz project I created for trying the solution.

What approach should I take for this? I know the general rule of dropdown is to show the option label in the view.


Solution

  • As the angular material recommends in their Select with custom trigger text example on mat-select, you can use the mat-select-trigger directive to specify what text should be displayed on the select trigger:

    <mat-form-field>
      <mat-label>Toppings</mat-label>
      <mat-select [formControl]="toppings" multiple>
        <mat-select-trigger>
          @if (toppings.value?.length === toppingList.length) {
            <span>ALL</span>
          } @else {
            {{toppings.value?.[0] || ''}}
            @if ((toppings.value?.length || 0) > 1) {
              <span class="example-additional-selection">
                (+{{(toppings.value?.length || 0) - 1}} {{toppings.value?.length === 2 ? 'other' : 'others'}})
              </span>
            }
          }
        </mat-select-trigger>
        @for (topping of toppingList; track topping) {
          <mat-option [value]="topping">{{topping}}</mat-option>
        }
      </mat-select>
    </mat-form-field>