0

In my Angular app, I have a <select> with a list of <option>s whose values are bound to objects.

I'm trying to get the last value selected using:

<select (change)="onSelect($event)">
   <option *ngFor="let option of myOptions;" [ngValue]="option"> {{ option.name }} </option>
</select>
onSelect(event: Event) {
  console.log(event);
}

So my options are bound to objects (myOptions is an array of objects).

This works fine and the {{ option.name }} (that is a string) is correctly displayed.

The problem is that the event.target.value in my onSelect will be a string like "1: Object", "2: Object", etc...

If I use [value] instead of [ngValue] the problem would be slightly different and the event.target.value would this time be the "[object Object]" string.

How can I get the real selected object option when emitting the (change) event?

Francesco Borzi
  • 56,083
  • 47
  • 179
  • 252

2 Answers2

0

I think you can't assign to value an object, it should be a string value. Take a look at this post Can the select option value be of different types?.

One option could be using an index to the array,

<select (change)="onSelect($event)">
   <option *ngFor="let option of myOptions; index as i;" [value]="i"> {{ option.name }} </option>
</select>

Or if you have an id in your option,

<select (change)="onSelect($event)">
   <option *ngFor="let option of myOptions" [value]="option.id"> {{ option.name }} </option>
</select>

You have a number of options to choose.

cabesuon
  • 4,860
  • 2
  • 15
  • 24
0

tried using below code

in html use ngModelChange instead of change event

<select [(ngModel)]="data" (ngModelChange)="dataChanged($event)" name="data">
      <option *ngFor="let currentData of allData" [ngValue]="currentData"> {{currentData.name}}</option>
</select>

in ts

allData = [{ name: "data1", id: 1 }, { name: "data2", id: 2 }];
dataChanged(event) {
    console.log(event); // here you will able to see whole object in console
  }

thanks

kushal shah
  • 823
  • 6
  • 9
  • @FrancescoBorzi i have got ans from https://stackoverflow.com/questions/44840735/change-vs-ngmodelchange-in-angular and https://stackoverflow.com/questions/45136548/angular-4-using-objects-for-option-values-in-a-select-list/45137528 link will help you for more – kushal shah Jan 27 '20 at 17:02