Saran S
Saran S

Reputation: 79

How to hide selected option from options list while using mat-select

I am using newest version mat-select v 16. When a particular option is selected and we click the select drop-down the selected option shouldn't show in options list. This is what I am using in html.

<mat-form-field>
    <mat-select formControlName="value" selected="option1">
      <mat-option *ngFor="let item of options"
         [value]="item.value">{{ item.label }}</mat-option>
    </mat-select>
</mat-form-field>

items consist of option1, option2, option3.

What do I need to use so that whenever option1 is in selected only option2 and option3 should show in dropdown??

Please reply!! TIA!!!

Upvotes: 0

Views: 954

Answers (2)

Tned
Tned

Reputation: 134

Try this:

1- In your TypeScript component, declare the selectedOption variable as an empty string and create a method to set its value:

selectedOption: string = '';

setSelectedOption(option: string) {
  this.selectedOption = option;
}

2- In your HTML, use this method to assign the selected value to selectedOption

<mat-form-field>
    <mat-select formControlName="value" [(ngModel)]="selectedOption">
        <mat-option *ngFor="let item of options" [value]="item.value" (click)="setSelectedOption(item.value)">{{ item.label }}</mat-option>
    </mat-select>
</mat-form-field>

Now, when you click on an option, the setSelectedOption method will be called to update the value of selectedOption with the selected option.

Upvotes: 0

Q.Rey
Q.Rey

Reputation: 713

you can do something like that by adding a class to hide the selected country via CSS

<mat-form-field>
  <mat-select name="countryVaraible" [(value)]="selectedCountry" placeholder="Country">
    <mat-option *ngFor="let country of countries" [value]="country.short" [ngClass]="country.short === selectedCountry ? 'hidden' : ''">
      {{country.full}}
    </mat-option>
  </mat-select>
</mat-form-field>


.hidden{
display: none;
}

Upvotes: 0

Related Questions