Javascript 如何用Angular2在楼上传递论点
我必须向函数传递一个参数Javascript 如何用Angular2在楼上传递论点,javascript,angular,Javascript,Angular,我必须向函数传递一个参数 <select class="chooseWatchlist" (change)="updateWatchlistTable(item.name)"> <option *ngFor="let item of _items">{{ item.name }}</option> </select> console.log(名称)返回未定义 如您所见,我需要该参数item.name,以使此http请求工作。感谢您的帮助。:
<select class="chooseWatchlist" (change)="updateWatchlistTable(item.name)">
<option *ngFor="let item of _items">{{ item.name }}</option>
</select>
console.log(名称)
返回未定义
如您所见,我需要该参数
item.name
,以使此http请求工作。感谢您的帮助。:) 使用NgModel
指令将所选值存储在组件的变量中,然后将该变量作为参数传递给http请求,我们调用该变量selectedValue
:
<select class="chooseWatchlist" [(ngModel)]="selectedValue"
(ngModelChange)="updateWatchlistTable(selectedValue)">
<option *ngFor="let item of _items" [ngValue]="item.name">{{ item.name }}</option>
</select>
阅读有关
NgModel
指令的更多信息。使用ngValue
可以绑定一个值和使用
(ngModelChange)=“$event.name”
您可以访问该名称。使用
[(ngModel)]=“selectedItem”
可以获取并设置所选项目
<select class="chooseWatchlist" [(ngModel)]="selectedItem" (ngModelChange)="updateWatchlistTable($event.name)">
<option *ngFor="let item of _items" [ngValue]="item">{{ item.name }}</option>
</select>
{{item.name}
您应该能够使用所选值传递给函数。为此,您可以从事件对象($event
)访问当前元素的值
{{item.name}
很酷,但对我来说,返回项.name
,而不仅仅是实际索引,这一点非常重要。但非常感谢您,向上投票。@H.Doe每次从下拉列表中选择值时,都会将item.name
存储在selectedValue
变量中。我会在测试中尝试您的解决方案,如果它比Gunther的解决方案效果更好,您可以确定我会将您的答案标记为最佳。@H.Doe您标记什么并不重要,我只想让您了解[ngValue]
中的值,在本例中,项.name
传递给selectedValue
变量。您可以使用[ngValue]=“item”
传递整个对象。
selectedValue: string;
<select class="chooseWatchlist" [(ngModel)]="selectedItem" (ngModelChange)="updateWatchlistTable($event.name)">
<option *ngFor="let item of _items" [ngValue]="item">{{ item.name }}</option>
</select>