Angular如何获取选定的选项(多个) [英] Angular how can I get selected options (multiple)
问题描述
我一直在寻找解决此问题的方法,已经两天了,但我找不到任何东西.基本上,我想要的是从我的<select>
元素中获取选定的选项:
I'm literally looking for the solution to this problem for two days and I can't find a thing... Basically what I want is to get selected options from my <select>
element:
<select name="selectedCars" [ngModel]="selectedCars" multiple>
<option *ngFor="let car of cars" [ngValue]="car">{{car.Model}}</option>
</select>
我认为它会绑定到selectedCars: Car[]
,我可以做这样的事情来显示选定的值:
I thought it would bind to selectedCars: Car[]
and I could do something like this to display selected values:
<h2>Selected:</h2>
<ul>
<li *ngFor="let selectedCar of selectedCars">{{selectedCar.Model}}</li>
</ul>
文档中实际上没有任何内容.
There's literally nothing in the documentation about this.
推荐答案
将[ngModel]
更改为[(ngModel)]
(双向绑定),这将在您选择/取消选择和下拉菜单中的选项后立即更新selectedCars
数组.
Change [ngModel]
to [(ngModel)]
(two way binding) which will update selectedCars
array as soon as you select / unselect and option in drop-down.
<select name="selectedCars" [(ngModel)]="selectedCars" multiple>
<option *ngFor="let car of cars" [ngValue]="car">{{car.Model}}</option>
</select>
否则,请在下面显示的select元素中添加以下属性,这与做[(ngModel)]
一样.
Otherwise do add below attribute to your select element shown below, it is one as the same thing doing [(ngModel)]
.
(ngModelChange)="selectedCars=$event"
这篇关于Angular如何获取选定的选项(多个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!