【问题标题】:How to get Selected Text and Selected Value of an ngSelect dropdown in angular 6如何在角度 6 中获取 ngSelect 下拉列表的选定文本和选定值
【发布时间】:2019-10-19 22:38:58
【问题描述】:

当表单发布时,我想在角度 6 中获取 ngSelect 下拉列表中的选定项目名称和值。

我尝试使用 ngModel 和 templateVariable 获取它,但未返回选定名称,我只设法获取选定值。

<ng-select
 name="testFunctionID"
 [items]="testFunctions"
 [multiple]="false"
 bindLabel="name"
 bindValue="testFunctionID"
 [(ngModel)]="model.testFunctionID">
</ng-select>

对于下拉列表 {Mumbai :1}, {Pune: 2}, {Delhi: 3},如果我选择 Pune,那么我应该得到“Pune”以及“2”作为输出 json。

【问题讨论】:

    标签: angular angular-ngselect


    【解决方案1】:

    我以前没有使用过那个包,但是我很好奇你的问题,我想我有一个答案。

    如果您在此处查看 https://github.com/ng-select/ng-select,它会在 API 输入部分表明

    bindValue - Object property to use for selected model. By default binds to whole object.

    所以我猜如果你省略 bindValue 属性,你将拥有整个对象,而不仅仅是 Id。

    还注意到有一个可以挂钩的事件

    (change) - Fired on model change. Outputs whole model


    问题作者指出无法使以下工作


    所以你可以做这样的事情。

    <ng-select
     name="testFunctionID"
     [items]="testFunctions"
     [multiple]="false"
     bindLabel="name"
     bindValue="testFunctionID"
     [(ngModel)]="model.testFunctionID"
     (change)="model.testFunctionName = $event.name">
    </ng-select>
    

    假设您要在模型和 ID 上设置名称属性。

    【讨论】:

    • 您的观察有所帮助。删除“bindValue”,我能够获得所选项目的完整对象。虽然第二个解决方案不起作用。
    • @MausamMalviya 很高兴听到它。我编辑了答案以表明第二种解决方案对您不起作用。可能有一些方法可以让它工作,我只是没有使用正确的语法是我的猜测。但我想留下它,以防它在未来引发其他人的想法。
    • @ccamac 您的第二个解决方案也适用。就我而言,我需要绑定到 id 而不是对象,但仍然需要获取标签来更新另一个字段并且能够成功使用 (change) 事件。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2019-01-22
    相关资源
    最近更新 更多