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.

0

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.