首页 > 解决方案 > Angular 6:使用复选框检索 ngFor 列表的元素

问题描述

我想在 Angular 上使用 ngFor 显示一个数组(我正在使用 Angular 6)。我希望能够通过单击复选框来选择我的一些汽车最后,当我按下按钮时,我将购买选定的汽车。

列表显示正常,复选框也是如此,但我真的不知道如何轻松检索选定的汽车。你能帮我吗?我已经尝试了一些我在 StackoverFlow 上找到的示例,但没有成功

我不想触摸仅包含 3 个字段(id 品牌和价格)的车型

<thead>
<button type="button" click="buySelectedCars()">BUY</button>
</tr>
<th>car id</th>
<th>car brand</th>
<th>car price</th>
<th> checkbox</th>
<tr>
</thead>
<tbody>
<tr *ngFor="let car of cars">
<td>{{car.id}}</td>
<td>{{car.brand}}</td>
<td>{{car.price}}</td>
<td>
<input type="checkbox" [checked]='car.check'></td>
</td>
</tr>
</tbody>

TS:

buySelectedCars(){
    for (car of cars){
    if car.check{
    this.carService.buyCar(car);
    }
    }
}

标签: angularngfor

解决方案


您可以维护一组检查项目。

例如:

html:

<td>
<input type="checkbox" [checked]='cars.indexOf(car) > -1' (change)="checkChanged(car)"></td>
</td>

ts:

//declare array

const cars = [];

//function
checkChanged(car)
{
  const checkedCar = this.cars.find(c => c.id === car.id);
  if(checkedCar)
  {
    this.cars.splice(this.cars.indexOf(checkedCar), 1);
  }
  else
  {
    this.cars.push(car);
  }
}

推荐阅读