3

Each plant has a plantid, plantname, role. I'm trying to get the entirety of the object back from the option selection.

   onChange(newValue){
      console.log(newValue)
      this.selectedPlant = newValue
    }
<select 
  *ngIf="plants" 
  class="form-control" 
  style="width:auto;" 
  #sel
  [(ngModel)]="selectedPlant"
  (ngModelChange)="onChange($event)"
  >
  <option 
   *ngFor="#plant of plants"
   [value]="plant.plantid"
   >{{plant.plantname}}</option>
</select>

If I set [value] = "plant", I get "[Object, Object]". I'm going to write a service to get one value from the other, but I feel like there should be a cleaner way to do this.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
SteveB
  • 155
  • 1
  • 9

2 Answers2

3

If you want to use objects as values instead of plain strings you have to use [ngValue] instead of [value]:

<select 
    *ngIf="plants" 
    class="form-control" 
    style="width:auto;" 
    #sel
    [(ngModel)]="selectedPlant"
    (ngModelChange)="onChange($event)">
  <option 
      *ngFor="let plant of plants"
      [ngValue]="plant">{{plant.plantname}}
  </option>
</select>
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
1

If you want the whole plant object, without changing much of your code you can do this-

onChange(plantid){
  console.log(plantid)
  this.selectedPlant = this.plants.filter((plant)=>{ return plant.plantid=== plantid;});
}

And in your html -

<select *ngIf="plants" class="form-control" style="width:auto;" #sel (ngModel)]="selectedPlant" (ngModelChange)="onChange($event.target.value)"> 
<option *ngFor="#plant of plants" [value]="plant.plantid">{{plant.plantname}}</option>

Hope that helps.

Rehban Khatri
  • 924
  • 1
  • 7
  • 19