我想获取我在下拉菜单中当前选择的元素的完整对象。目前,我得到了选定的值,这对我来说很好!但另外我想获得完整的对象。我该怎么办?
<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"}
}
答案 0 :(得分:0)
为此使用[ngValue]="item"
和[compareWith]="compareData"
。
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>
答案 1 :(得分:-1)
就做
fn_consolidadoUsuario(){
const mySelectedUser = this.aUser.find(cursor => cursor.iduser === this.user);
}