0
votes

I have used below code to update model value based on certain condition using md-select material component. When I select particular option first time i.e., tacos-2 in md-select component, at that time model value updating properly. But after that again selecting same option i.e., tacos-2 in the md-select component, at that time model value not updating properly.

app.component.ts:-

export class App {
  name:string;
  foods = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'}
  ];
  selectedValue: string = this.foods[0].value;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
  onFoodChanged(event) {
    if(this.selectedValue == "tacos-2") {
      this.selectedValue = "pizza-1";
    }
    event.value = this.selectedValue;
    console.log(event)
  }
}

app.component.html:-

<md-select placeholder="Favorite food" [(ngModel)]="selectedValue" name="food"
     (change)="onFoodChanged($event)">
    <md-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </md-option>
</md-select>

Demo:- https://plnkr.co/edit/rugT0PtmpP1gtHDzWReY?p=preview

How can I update model value on md-select component onchange event?

2

2 Answers

2
votes

(change) event is bound to the value changes. If you are looking to check model changes, use (ngModelChange) instead. But in both cases your (onFoodChanged) would've be fired if there is no actual change to the value/model. So if you are looking to detect whenever an option is selected, it's better to check (click) event on options:

<md-select placeholder="Favorite food" [(ngModel)]="selectedValue" name="food">
    <md-option (click)="onFoodChanged($event)" *ngFor="let food of foods"  
               [value]="food.value">
          {{food.viewValue}}
        </md-option>
    </md-select>

DEMO

-1
votes

I have used setTimeout() function inside md-select change event. Now my model value is updating properly.

onFoodChanged(event) {
  setTimeout(()=> {
    if(this.selectedValue == "tacos-2") {
      this.selectedValue = "pizza-1";
    }
  }, 0);
}

Demo:- https://plnkr.co/edit/iZFmK0Kfui9NSeYybk8Q?p=preview