【问题标题】:Angular how can I get selected options (multiple)Angular如何获得选定的选项(多个)
【发布时间】:2017-04-27 19:12:00
【问题描述】:

我实际上是在寻找这个问题的解决方案两天,但我找不到任何东西......基本上我想要的是从我的 <select> 元素中获得选定的选项:

<select name="selectedCars" [ngModel]="selectedCars" multiple>
    <option *ngFor="let car of cars" [ngValue]="car">{{car.Model}}</option>
</select>

我认为它会绑定到selectedCars: Car[],我可以这样做来显示选定的值:

<h2>Selected:</h2>
<ul>
    <li *ngFor="let selectedCar of selectedCars">{{selectedCar.Model}}</li>
</ul>

文档中几乎没有关于此的任何内容。

【问题讨论】:

    标签: angular


    【解决方案1】:

    [ngModel] 更改为[(ngModel)](双向绑定),一旦您在下拉菜单中选择/取消选择和选项,就会更新selectedCars 数组。

    <select name="selectedCars" [(ngModel)]="selectedCars" multiple>
        <option *ngFor="let car of cars" [ngValue]="car">{{car.Model}}</option>
    </select>
    

    否则,请在如下所示的选择元素中添加以下属性,这与 [(ngModel)] 的操作相同。

    (ngModelChange)="selectedCars=$event"
    

    【讨论】:

      【解决方案2】:

      你应该使用[(ngModel)]

      <select name="selectedCars" [(ngModel)]="selectedCars" multiple>
                <option *ngFor="let car of cars" (click)="clickedOption()" [ngValue]="car">
                {{car.name}}</option>
            </select>
      
      clickedOption(){
          console.log(this.selectedCars)
        }
      

      您可以在单击选项时简单地记录元素,如上述方法所示

      LIVE DEMO

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-17
        • 1970-01-01
        • 2018-11-11
        • 2012-02-21
        • 1970-01-01
        • 1970-01-01
        • 2021-10-12
        • 1970-01-01
        相关资源
        最近更新 更多