【问题标题】:Get full item of a dropdown in a *ngFor [duplicate]在 *ngFor 中获取下拉列表的完整项目 [重复]
【发布时间】:2019-06-26 12:04:18
【问题描述】:

我想获取我当前在下拉列表中选择的元素的完整对象。目前我得到了选定的值,这对我来说很好!但另外我想获得完整的对象。我该怎么做?

<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"}
}

【问题讨论】:

    标签: angular


    【解决方案1】:

    做事

    fn_consolidadoUsuario(){
      const mySelectedUser = this.aUser.find(cursor => cursor.iduser === this.user);
    }
    

    【讨论】:

    • 这可能会解决 OP 的问题,但如果它也解释了 为什么 它解决了 OP 的问题会更有帮助。有效的代码远不如您理解的有效的代码有用:)
    【解决方案2】:

    为此使用[ngValue]="item"[compareWith]="compareData"

    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>
    

    【讨论】:

      猜你喜欢
      • 2016-07-29
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 2015-08-21
      • 2021-05-17
      相关资源
      最近更新 更多