如何在angular2中的选择更改事件中获取值

问题描述 投票:6回答:2

我想使用动态生成的选择下拉列表进行导航。看起来我不能直接这样做,所以我只想在select更改时进行函数调用。

要做到这一点,我有这个:

---在模板中---

<select (change)="navSelected($event)">
    <option *ngFor="let button of navButtons;"
    value="button.route" >{{button.label}}</option>
</select>

足以说'navButtons'是一个具有'label'字段的对象数组。

- -在课堂里 - -

navSelected(navName) {
    console.log(navName + " Clicked!");
}

这实际上很好。

我从Mark Rajcok的大力帮助中得到了这一点,以及他在这个老问题中的回答:How can I get new selection in "select" in Angular 2?

也就是说,我希望能够在navSelected()函数调用中传递选定的值。我不确定该怎么做。

我尝试将[ngValue]="button"添加到其他搜索到选项标签的狂野猜测中,然后在button事件处理程序中引用(change)变量(所以:(change)="navSelected(button.label)"和其他组合,无济于事。我看过很多对ngModel的引用但是它们看起来很旧,我不完全确定它们已经适用了(我无法让它们在RC4中工作)。

我可能会拉一些jquery或其他任何东西来找到选择并获得它的值,但这似乎非常无聊 - 与仅仅能够正确调用函数相比。

javascript angular
2个回答
11
投票

您正在寻找的值是$event.target,您可以使用$event.target.value获取它,请参阅下面的示例。

navSelected($event) {
    console.log($event.target.value + " Clicked!");
}

如果您希望获得选项的选定文本,则可以执行此操作

navSelected($event) {
    let selectElement = $event.target;
    var optionIndex = selectElement.selectedIndex;
    var optionText = selectElement.options[optionIndex];
    console.log(optionText + " Clicked!");
}

1
投票

作为@eltonkamami的答案的快捷方式,您可以像这样传递您的对象:

<select (change)="navSelected(navButtons[$event.target.selectedIndex])">
    <option *ngFor="let button of navButtons;">{{button.label}}</option>
</select>

并捕获它像这样:

navSelected(button: [type of navButtons]){
    console.log(button);
}
© www.soinside.com 2019 - 2024. All rights reserved.