Piosek
Piosek

Reputation: 260

Angular material select - problem with displaying selected value

Im using angular material select: https://material.angular.io/components/select/examples

And in my app Im using a lot of select inputs and they all have shared option array between all of them. Example array of options:

  foods: Food[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'}];

And my problem is: when I select any value and then I reset my option array for example with button click, then selected value dissapears from all select inputs.

Is there any way to keep the selected value visible on select input when I reset select option array or when I put explicitly new values into option array?

Edited:

To be more clear, lets consider this code:

TS file:

foods: Food[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'}];

selected = 'pizza-1';

resetOptions() {
    this.foods = [];
}

HTML:

<mat-form-field>
    <mat-label>Favorite food</mat-label>
    <mat-select name="food" [(value)]="selected">
      <mat-option *ngFor="let food of foods" [value]="food.value">
        {{food.viewValue}}
      </mat-option>
    </mat-select>
</mat-form-field>

<p>{{selected}}</p>

<button (click)="resetOptions()">Reset Options</button>

And when I select value, the 'selected' propety corectly updates value and this value appears on select input, but when I click 'Reset Options' button, 'selected' propety still keeps its value, but that value disappears from select input.

Upvotes: 0

Views: 1631

Answers (1)

Hassan Siddiqui
Hassan Siddiqui

Reputation: 2845

HTML

<mat-form-field>
    <mat-label>Favorite food</mat-label>
    <mat-select name="food" [(value)]="selected">
      <mat-option *ngFor="let food of foods" [value]="food.value">
        {{food.viewValue}}
      </mat-option>
    </mat-select>
</mat-form-field>

TS

selected = 'pizza-1';

foods: Food[] = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'}
];

Try above code snippet, I hope it'll help you out. Thanks

Upvotes: 0

Related Questions