Enthu
Enthu

Reputation: 532

ngModel shows previous value selected on md-select

When I console log selectedVendor in the method vendorUpdate it shows the previous value of selectedVendor instead of the new value.

<div>
   <md-select id="vendorVariable" class="vm-select-wrap" 
              (ngModelChange)="vendorUpdate()"
              [(ngModel)]="selectedVendor" placeholder="AWS" 
              name="vendorVariable">
      <md-option *ngFor="let vendor of vendors" value={{vendor.small}}>
          {{vendor.caps}}
      </md-option>
   </md-select>
</div>

TS file:

vendors: any = [
   {caps: "AWS", small: "aws"},
   {caps: "AZURE", small: "azure"}
];

selectedVendor :any;                    

vendorUpdate(){
  this.selectedVendor = this.selectedVendor;
  console.log(this.selectedVendor);  
}

On selecting the value from select dropdown selectVendor prints the previous selected value, whereas the current selected value should be printed.

Upvotes: 2

Views: 2109

Answers (2)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

You don't need ngModelChange actually, if you don't want to do any dependent operation, [(ngModel)] will do rest of the thing (two way binding).

<md-select id="vendorVariable" class="vm-select-wrap" [(ngModel)]="selectedVendor" placeholder="AWS" name="vendorVariable">
  <md-option *ngFor="let vendor of vendors" [value]="vendor.small">
    {{vendor.caps}}
  </md-option>
</md-select>

Demo Here

Upvotes: 2

AVJT82
AVJT82

Reputation: 73357

[(ngModel)] basically equals: [ngModel] and (ngModelChange). So I would suggest to use either.

You can skip the ngModelChange if you use two-way binding like Pankaj suggested. Otherwise you can also use one-way binding and ngModelChange. as a sidenote you can also use [value]="vendor.small" instead of value="{{vendor.small}}. with [ ] we bind the variable.

<md-select [ngModel]="selectedVendor" (ngModelChange)="vendorUpdate($event)">
   <md-option *ngFor="let vendor of vendors" [value]="vendor.small">
      {{vendor.caps}}
   </md-option>
</md-select>

TS:

vendorUpdate(value) {
  this.selectedVendor = value;
  console.log(this.selectedVendor);
}

Upvotes: 3

Related Questions