我想导航使用动态生成的选择下拉列表。 看起来我不能直接这样做,所以我只想在选择更改时进行函数调用。
要做到这一点,我有这个:
---在模板---
<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或其他任何东西来找到select并得到它的值,但与简单地能够正确调用函数相比,这似乎非常简陋。
答案 0 :(得分: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 :(得分: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);
}