JSON Object as Select value - Angular 2

0

Object

export class Car {
  ID: String;
  dors: [{
    number: Number,
    postion: {
        x: String,
        y: String,
        z: String,
    }
  }]

}

It is possible to define the value of a select as an object and not a simple string . I do not mean the object to show but the value . I tried using value={{}} but it seems to only work with string . I tried doing it with ngValue , but it seems not to change the behavior. Is it possible to do it?

I want car.dors.position as value

I tried:

<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>
    
asked by Mario López Batres 12.01.2018 в 12:50
source

1 answer

1

Do it in the following way, add ngModel .

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

selectedDoor is an Object of the Door type, since the option for "default" (preselected), can be an object without value, but d should be of the same type as the Value .

  

[value]="..." -> Only supports Strings.

     

[ngValue]="..." - > Supports any Object - You need a ngModel

Remember: add to your Module import { FormsModule } from '@angular/forms';

    
answered by 12.01.2018 в 13:56