bellotas
bellotas

Reputation: 2461

Object JSON as value in Angular2

I show in one select one string as an option and it works. My problem is that I would like to get the whole JSON object as the value of this option but I get the string that I am showing.

My code is the following:

    <select *ngIf="car" class="form-control" #oneDoor  (change)="getRecDet(oneDoor.value);"  required >
          <option *ngFor="let oneDoor of car.doors" [ngValue]="oneDoor">{{oneDoor.position}}</option>
    </select>

I explain it: car and object car car is the object of one car. The object is like the following:

   export class Car {
     name: String;
     doors: [{
       position: String
     }]
   }

So I am trying to show just for each door the position. That works but I would like that the value that I get from the select (not the one that I am showing, just the one that I get in my backend) would be the whole object (name, doors, position) but I am just able to get the String

I know that value={{}} gets only a string, so I was trying it with ngValue but it keeps happening the same. Any idea?

Upvotes: 2

Views: 396

Answers (1)

Igor
Igor

Reputation: 62213

You should bind it to ngValue using the "box" syntax: [value].

<select  #coche (change)="getCoches(coche.value);" >
    <option type="text" *ngFor="let coche of coches" [ngValue]="coche">{{coche.nombre}}</option>                       
</select>

value is only supported for strings. If you want to bind to an object then you should use ngValue and bind to it using the "box" notation.

Upvotes: 1

Related Questions