19

I have a mat-select dropdown, here I am looping through my frequencyArr object.

In ts

frequencyArr = [
{key : "Once daily", abbriviation : '0-0-1'},
{key : "Twice daily", abbriviation : '1-0-1'},
{key : "Thrice daily", abbriviation : '1-1-1'},
{key : "Four times a day", abbriviation : '1-1-1-1'}
  ]

In html

<mat-select placeholder="frequency" formControlName="frequency" required>                             
    <mat-option *ngFor="let frequency of frequencyArr" [value]="frequency.abbriviation">
        <span>{{frequency.key }} : {{ frequency.abbriviation}}</span>
    </mat-option>
</mat-select>

What I am trying to do is when open the dialog it will show object key : object value-

<span>{{frequency.key }} : {{ frequency.abbriviation}}</span>

enter image description here

This is fine, but when I select the option it should show only frequency.key into selected field which is not happening.

enter image description here

I tried googling but did not find anything for this case. Any help is appreciated.

GCSDC
  • 3,138
  • 3
  • 28
  • 48
Rahul Pandey
  • 435
  • 1
  • 3
  • 13

2 Answers2

16

You can do the following to accomplish this.

Set your value to frequency.key

[value]="frequency.key"

Then use <mat-select-trigger to display the frequency.value from your formControl

<mat-select-trigger>
      {{frequency.value}}
    </mat-select-trigger>

Stackblitz

https://stackblitz.com/edit/angular-wxv1wv?embed=1&file=app/select-custom-trigger-example.html

Marshal
  • 10,499
  • 2
  • 34
  • 53
  • This is not working. In my case frequency is a FormGroup element instead of FormControl. I am not sure if that is the reason? – Rahul Pandey Mar 14 '19 at 20:52
  • You are correct, please see revised stackblitz. `{{myFormGroup.controls['frequency'].value}}` – Marshal Mar 14 '19 at 21:03
14

You may achieve that by using a mat-select-trigger and a template reference as bellow:

<mat-select placeholder="frequency" required #select>
  <mat-select-trigger>
    {{ select.value?.abbriviation }}
  </mat-select-trigger>
  <mat-option *ngFor="let frequency of frequencyArr" [value]="frequency">{{frequency.key }} : {{ frequency.abbriviation}}</mat-option>
</mat-select>
GCSDC
  • 3,138
  • 3
  • 28
  • 48