首页 > 解决方案 > 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>

标签: angularcheckbox

解决方案


有不同的方法可以解决这个问题。首先想到的是将颜色信息存储在汽车对象本身内。所以你的汽车界面看起来像这样:

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}} €&lt;/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


推荐阅读