Home > Back-end >  How do I put image inside mat-select-trigger?
How do I put image inside mat-select-trigger?

Time:08-10

I have two svg flag images in my assets file, how can I put these images in mat-select-trigger according to the language the user selects? Below is my code for viewing and adding the resolution please.

enter image description here enter image description here

HTML

<div >
        <mat-select  [(value)]="selectedLanguage" #selLang (selectionChange)="setLang(selLang.value)" disableOptionCentering>
            <mat-option value="pt-br">
                <img  [src]="'./assets/flagIcons/br_flag.svg'">
                {{ 'header.language.pt-br' | translate }}
            </mat-option>
            <mat-option value="en">
                <img  [src]="'./assets/flagIcons/usa_flag.svg'">
                {{ 'header.language.en' | translate }}
            </mat-option>
        </mat-select>
    </div>

TS

constructor(private readonly translate: TranslateService) {}

     public setLang(lang: string) {
            this.translate.use(lang);
        }

SVG Images on file Assets

enter image description here

CodePudding user response:

First of all, I recommend you wrap the mat-select with mat-form-field. More info here: https://material.angular.io/components/form-field/overview

In your case you can use matPrefix directive:

<mat-form-field>
  <mat-select>
    <mat-option value="value">
      <!-- Option text -->
    </mat-option>
  </mat-select>

  <span matPrefix>
    <!-- Your image here -->
  </span>
</mat-form-field>

CodePudding user response:

I managed to solve it this way.

<div >
            <mat-select  [(value)]="selectedLanguage" #selLang (selectionChange)="setLang(selLang.value)" disableOptionCentering>
                <mat-select-trigger>
                    <img [src]="selectedLanguage === 'en' ? './assets/flagIcons/usa_flag.svg' : './assets/flagIcons/br_flag.svg'">
                    {{ selectedLanguage === 'en' ? ('header.language.en' | translate) : ('header.language.pt-br' | translate) }}
                </mat-select-trigger>
                <mat-option value="pt-br">
                    <img  [src]="'./assets/flagIcons/br_flag.svg'">
                    {{ 'header.language.pt-br' | translate }}
                </mat-option>
                <mat-option value="en">
                    <img  [src]="'./assets/flagIcons/usa_flag.svg'">
                    {{ 'header.language.en' | translate }}
                </mat-option>
            </mat-select>
        </div>
  • Related