angular - 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);
}
}
}
解决方案
您可以维护一组检查项目。
例如:
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);
}
}
推荐阅读
- visual-studio - 安装 Microsoft.AspNet.Odata 时未定义 System.Web.OData
- python - 具有不同线程 ID 的 ROS TimeSynchronizer 回调
- html - 嵌入式 HTML 文档中的 CSS 是否会影响“父”HTML 文档
- rust - 原始变量的寿命不够长
- spring-boot - aws elasticsearch签名删除请求返回403禁止(使用apache httpclient)
- angular - Angular 一次在多个地方使用相同的 TemplateRef - 克隆 TemplateRef?
- excel - 执行时忽略“FillDown”代码
- css - 无法将 SCSS 值分配给 css 自定义属性(css 变量)
- java - 如何使用java根据Key值更新XML文件值
- c++ - 现代 CMake (3.8+) - FindCUDA 已弃用,非 .cu 文件呢?