How to display icon inside angular material select <mat-option> and selection of the same

Viewed 11252

How to correctly display icon inside the select drop down control using material select control. After selecting mat option its selecting text of icon as well how to overcome this issue ?

            <mat-form-field>
                <mat-select formControlName="genderFormControl" placeholder="Gender">
                    <mat-option>None</mat-option>
                    <mat-option *ngFor="let gender of genders" [value]="gender.value">
                            <mat-icon matListIcon>pregnant_woman</mat-icon>
                            {{gender.name}}
                    </mat-option>
                </mat-select>
            </mat-form-field>

enter image description here


enter image description here

3 Answers

You can get it done via the "mat-select-trigger" option.

  <mat-select-trigger>
      <mat-icon>pregnant_woman</mat-icon>&nbsp;{{gender.name}}
   </mat-select-trigger>

More Documentation on mat-select-trigger.

Complete code

<mat-form-field>
    <mat-select formControlName="genderFormControl" placeholder="Gender">
        <mat-option>None</mat-option>
        <mat-option *ngFor="let gender of genders" [value]="gender.value">
                <mat-icon matListIcon>pregnant_woman</mat-icon>
                {{gender.name}}
        </mat-option>

        <!-- MUST USE mat-select-trigger TO SHOW mat-icon -->
        <mat-select-trigger *ngIf="gender.value === 'f'">
            <mat-icon>pregnant_woman</mat-icon>&nbsp;{{gender.name}}
        </mat-select-trigger>
    </mat-select>
</mat-form-field>

Like the others said, you need to use mat-select-trigger to show set what the field looks like after you've selected an option.

This code worked in our project:

<mat-form-field appearance="outline" style="width: 100%">
    <mat-label>Work Ownership</mat-label>
    <mat-select [formControl]="missionForm.controls.type">
        <mat-option *ngFor="let type of missionTypes" [value]="type">
            <mat-icon *ngIf="type == 'individual'">person</mat-icon>
            <mat-icon *ngIf="type == 'group'">groups</mat-icon>
              {{ type }}
        </mat-option
            >
            <mat-select-trigger> {{ missionForm.controls.type.value }} </mat- 
            select-trigger>
    </mat-select>
</mat-form-field>
Related