0

I want to obtain the complete object of the element that I currently have selected in my dropdown. Currently I get the selected value and this is fine for me! but additional I want to obtain the complete object. How can I do it?

<select  [(ngModel)]="user" (change)="fn_consolidadoUsuario()"  mdbInput    > 
    <option *ngFor="let item of aUser" [value]="item.iduser">{{item.name}} 
    </option>

user:any
aUser:
[
{
    "iduser":1, "name":"joe"
},
{
    "iduser":1, "name":"berta"
},
{
    "iduser":1, "name":"francisco"
}
]


this.user=1; //value by default

fn_consolidadoUsuario(){
 console.log(this.user)// 1
 //also I need the actual item    {"iduser":1, "name":"joe"}
}
user5115790
  • 61
  • 1
  • 6

2 Answers2

0

use [ngValue]="item" and [compareWith]="compareData" for this.

Stackblitz Demo

component.ts

user:any={"iduser":2,"name":"berta"} 

aUser=[
    {"iduser":1, "name":"joe"},
    {"iduser":2, "name":"berta"},
    {"iduser":3, "name":"francisco"}
]

fn_consolidadoUsuario(){
    console.log(this.user)
}

compareData(a, b) {
    return a && b && a.iduser == b.iduser;
}

component.html

<select  [(ngModel)]="user" (change)="fn_consolidadoUsuario()"  mdbInput  [compareWith]="compareData"  > 
    <option *ngFor="let item of aUser" [ngValue]="item">{{item.name}} 
    </option>
</select>

<pre>{{user | json}}</pre>
Krishna Rathore
  • 9,389
  • 5
  • 24
  • 48
-1

Just do

fn_consolidadoUsuario(){
  const mySelectedUser = this.aUser.find(cursor => cursor.iduser === this.user);
}
  • This may solve OP's problem, but it would be more helpful if it also explained *why* it solves OP's problem. Code that works is much less helpful than code that works **and** you understand :) – MyStackRunnethOver Feb 01 '19 at 22:03