Assign JSON object to value in Angular2

0

Hi, I've done a couple of tests in Angular 2, and I'd like to resolve a question.

Right now I'm working with a simple select, and I'm trying to receive a JSON object by making a selection in it.

WORKS It works if I want to receive only a part of the JSON (attached an example):

JSON

export class Coche{
  nombre: String;
  dueños: [{
    nombre: String;
  }];
  vendedores: [{
    nombre: String;
  }];
}

If I do the following, it works: HTML

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

TS

   getCoches(nombre: string): void {
        console.log(scenario);
}

DOES NOT WORK But if I do the following, no:

HTML

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

TS

 getCocches(coche: Coche): void {
        console.log(coche);
}

The difference is that I send a complete object (car) and not an element of it (car.name). Any solution?

    
asked by Mario López Batres 11.12.2017 в 16:32
source

1 answer

0

As I understand you want to send the car object as a value, right ?, I will set an example as I would:

Componente.html
<select [(ngModel)]="cocheSelected" name="select-coche" required>
<option selected="true" disabled="disabled">Selecciona un coche</option>
<option *ngFor="let coche of coches" [ngValue]="coche">{{coche.Modelo}}</option>
</select>

Componente.ts
export class Coche {
   coches: Coche[] = [{Id: 1, Modelo: "Scania S"}, {Id: 2, Modelo: "Volvo XL"}];
   cocheSelected: Coche;
   constructor() {}
}

That would be the way to use Select with Object, the primitive form would be:

Componente.ts
cocheSelected = null;
public coches= [
    {Id: 1, Modelo: "Scania S"}, {Id: 2, Modelo: "Volvo XL"}
];

Componente.html
<select name="select-coche" [(ngModel)]="cocheSelected">
        <option *ngFor="let coche of coches" [value]="coche.Id">  
        {{coche.Modelo}}
        </option>
    </select>

I hope to be understandable :-D

    
answered by 13.12.2017 в 01:12