skip to Main Content

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!!!

2

Answers


  1. 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;
    }
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search