Arm144
Arm144

Reputation: 773

Hide selected option in Mat-Select

I`m wondering if I could in a select of angular material 2 hide the selected option. So I have this right now:

<mat-form-field>
    <mat-select placeholder="{{ 'NAVBAR.LANG' | translate }}"  (change)="langSelected($event.value)" panelClass="panelResponsive">
        <mat-option *ngFor="let language of languages" [value]="language.value">
          <span>{{language.lang}}
            <span>
              <img src="{{language.img}}">
            </span>
          </span>
        </mat-option>
    </mat-select>
  </mat-form-field>

My languages array is:

languages = [
    {
        'lang': '',
        'value': 'es-ES',
        'img': '/assets/images/languages/spainIco.png',
        'alt': 'SP'
    }, {
        'lang': '',
        'value': 'en-GB',
        'img': '/assets/images/languages/ukIco.png',
        'alt': 'UK'
    }
];

What I want to do is that if I choose spanish, the next time I open the dropdown, only appears the English option, and vice versa.

Thanks you all.

Upvotes: 3

Views: 9183

Answers (2)

Experimenter
Experimenter

Reputation: 2478

You can hide mat-option by css property display: none . For that you can add specific class e.g. "d-none"

In html:

<mat-option *ngFor="let languageOption of languages" [value]="languageOption.value" [ngClass]="{'d-none': isAlreadySelectedLanguageOption(languageOption )}">

In ts:

isAlreadySelectedLanguageOption(languageOption): boolean {
    return this.form.languages.some((language) => language.value === languageOption.value);
}

Upvotes: 0

user4676340
user4676340

Reputation:

Sure, use a getter to filter the list of languages :

get filteredLanguages() {
  return this.selectedLanguage ? 
    this.languages.filter(language => language.value !== this.selectedLanguage.value) : 
    this.languages;
}
<mat-option *ngFor="let language of filteredLanguages" [value]="language.value">

Upvotes: 3

Related Questions