angular - Angular:从列表中链接两个不同的复选框
问题描述
我一直在努力实现一个列表,其中有两个相互依赖的复选框。
基本上,我有一个汽车清单。在其中一些上,我想将它们选择为蓝色或红色。如果我说 on 是蓝色的,我希望取消选中该复选框。
我能怎么做?
<tr *ngFor="let car of cars |let i = index;">
<td>
{{ car.id}} €
</td>
<td>
<input type="checkbox" value="car.id" (change)="onCarBlue($event,i)">
</td>
<td>
<input type="checkbox" value="car.id" (change)="onCarRed($event,i)">
</td>
</tr>
解决方案
有不同的方法可以解决这个问题。首先想到的是将颜色信息存储在汽车对象本身内。所以你的汽车界面看起来像这样:
interface Car {
id: number;
color?: 'blue' | 'red'; // This one is added as optional property
}
然后,在您的 html 中,您可以使用该属性来决定是否选中了复选框:
<tr *ngFor="let car of cars; let i = index;">
<td>{{car.id}} €</td>
<td>
<input
type="checkbox"
[checked]="car.color === 'blue'"
(change)="onCarColorChange(i, 'blue')">
</td>
<td>
<input
type="checkbox"
[checked]="car.color === 'red'"
(change)="onCarColorChange(i, 'red')">
</td>
</tr>
最后,在您的 component.ts 中,您需要对更改做出反应并设置变量:
public onCarColorChange(index:number, color: 'blue' | 'red') {
// Do mind: You need to create a new Array for Angular change detection
// to pick up that the color has changed
this.cars = this.cars.map((car, i) => i === index
? {...car, color} // Change the color of the car at the given index
: car // Return an unchanged car for all other indexes
);
}
我创建了一个 StackBlitz 来证明这一点: https ://stackblitz.com/edit/angular-k1ky1w
推荐阅读
- python - 大熊猫数据帧上的多处理突然变慢
- reactjs - 如何使用 yup 验证检查电子邮件 ID 是否已存在?
- python - 删除重复项,但将一列的数据保留在新列中
- oracle - 无法使用带有 Spring Data 反应式存储库的 Oracle R2DBC 驱动程序执行任何查询
- c++ - 如何在模板专业化 C++ 中重命名字段
- javascript - 使用 Flask 后端和 React 前端登录
- c++ - 当联合成员是整数时,字节序会影响联合成员吗?
- laravel - 在单元测试中将数据保存到数据库
- html - Django表单,html标签在前端显示为文本
- javascript - 如何为 ReactJS 创建类似于 Facebook 功能的更改头像框架?