Angular dynamic flag icon in span based on mat-select change

Issue

I have a mat-select and I would like to change a flag icon in a span in the mat-label, based on the selected option.

The initial flag is shown, after a click no change occurs in the span.

The flags in the option list are working correctly, so the question only concerns the label.

I am trying something like:

HTML:

    <mat-form-field>
    <mat-label>
      <span [class]="getLanguageFlag(selectedLanguage)"></span>
      {{ selectedLanguage }}
    </mat-label>

    <mat-select
      [(ngModel)]="selectedLanguage"
      name="selectedLanguage"
      id="selectedLanguage"
    >

      <mat-option
        *ngFor="let language of languages"
        [value]="language"
        (click)="changeLanguage(language)"
      >

        <span [class]="getLanguageFlag(language)"></span>
        {{ language }}
      </mat-option>
    </mat-select>
  </mat-form-field>

TS:

    selectedLanguage: string = environment.defaultLanguage;

    constructor(
    private store: Store<State>,
    private translateService: TranslateService) {}

    changeLanguage(language: string): void {
    this.selectedLanguage = language;
    }

    getLanguageFlag(language: string): string {
    let style = 'flag-icon flag-icon-';
    return language === 'en' ? `${style}gb` : `${style}${language}`;
    }

I’ve also tried a getter/setter, but the setter didn’t seem to work when using the mat-select.

Thanks in advance for your help!

Solution

I tested it and you code works. You should just check if 2-letter country code is correct.

I don’t know if you just didn’t copy it correctly, but you are missing closing <mat-form-field> tag in you HTML, so check that also.

Working example

Answered By – NeNaD

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.