Josf
Josf

Reputation: 786

Angular material group dropdown - How to add group name to text box

I have a material group dropdown designed just like the official documentation (here).

Question is : How can I display the selected item text along with group name.

ie; If I select Bulbasaur from 'Grass' group, as in the image, it should show 'Grass - Bulbasaur' instead of just 'Bulbasaur'. Any ideas?

enter image description here enter image description here

Update: I have found a work around. Anyone fiddling around with the same issue can do this css hack in the mean time,

<mat-form-field>
 <mat-select placeholder="Pokemon" [formControl]="pokemonControl">
  <mat-option>-- None --</mat-option>
   <mat-optgroup *ngFor="let group of pokemonGroups" [label]="group.name"
              [disabled]="group.disabled">
    <mat-option *ngFor="let pokemon of group.pokemon" [value]="pokemon.value">
     <span style=display:none">{{group.name}} -</span>{{ pokemon.viewValue }}
    </mat-option>
  </mat-optgroup>
 </mat-select>
</mat-form-field>

Upvotes: 1

Views: 2902

Answers (1)

benzeno
benzeno

Reputation: 691

It looks like the proper way to do this is to set "custom trigger text":

See the examples for the MatSelect instead of the overview

So you would do something like this:

<mat-form-field>
  <mat-select placeholder="Pokemon" [formControl]="pokemonControl">
    <mat-select-trigger *ngIf="pokemonControl.value; let pokemon">
      {{ pokemon.parentViewValue }} : {{ pokemon.viewValue }}
    </mat-select-trigger>
    <mat-option>-- None --</mat-option>
    <mat-optgroup *ngFor="let group of pokemonGroups" [label]="group.name"
                  [disabled]="group.disabled">
      <mat-option *ngFor="let pokemon of group.pokemon" [value]="pokemon">
        {{pokemon.viewValue}}
      </mat-option>
    </mat-optgroup>
  </mat-select>
</mat-form-field>

Take note of two things:

  1. Obviously the mat-select-trigger tag... I am using the full pokemon model, you will need to add either a reference to the parent group or, like I have done, add the parent view value in each pokemon. You can do either when you actually construct the model
  2. My [value] for the mat-option tag is pokemon instead of pokemon.value as I need the full model

Upvotes: 1

Related Questions