为什么 angular ngFor 组件共享相同的变量

Why are angular ngFor components sharing the same variables

我正在制作问题列表(问题名称和 yes/no 复选框)

问题是,当我点击第二个问题的复选框时,它仍然会更改第一个组件中的复选框。

这是我的代码:

渲染问题列表:

<div *ngFor="let question of questions">
  <app-question [question]="question"></app-question>
</div>

每题:

<div class="question">
    {{question}}
    <div class="checkboxes">
        <label class="checkbox-label">
            <input class="checkbox" [(ngModel)]="checked.yes" (ngModelChange)="checkboxChanged('yes')" type="checkbox" id="check1"/>
            <label for="check1" class="custom-checkbox"></label>
        </label>
        <label class="checkbox-label">
            <input class="checkbox" [(ngModel)]="checked.no" (ngModelChange)="checkboxChanged('no')" type="checkbox" id="check2"/>
            <label for="check2" class="custom-checkbox"></label>
        </label>
    </div>
</div>

checkboxChanged(value): void {
    value === 'yes' ? this.checked["no"] = false : this.checked["yes"] = false;
}

谢谢

编辑: https://stackblitz.com/edit/angular-59bkvw

解决方法: 问题是我的输入和标签在组件之间共享相同的 ID。 我分配了一个唯一的 ID,如 id="{{question}}" 并且它有效。谢谢大家的帮助。

我已经检查了你的代码,但无法重现你的问题,你需要提供完整的代码,否则最好创建一个 stackblitz 实例。

这是我使用您提供的代码创建的 stackblitz 实例:https://stackblitz.com/edit/angular-k73iqa

如果您有包含 Yes/No 个答案的问题列表,我建议您使用单选按钮。

查看此 stackblitz 示例。

<div class="question">
    {{question.text}}
    <input type="radio" value="yes" [name]="answer + question.id" [(ngModel)]="question.answer">Yes
    <input type="radio" value="no" [name]="answer + question.id" [(ngModel)]="question.answer">No
</div>

问题出在 CSS,而不是 Angular。从 question.component.css 中删除以下 CSS 后,它将开始工作:

.checkbox {
    opacity: 0;
}
.checkbox-label{
    position: relative;
}

到目前为止,我发现您有一个与 label for attribute 有关的问题和 输入 id。问题是 id 不是唯一的,所有输入元素都具有相同的 id。要解决这个问题,您必须动态生成 id:

将元素的索引作为 id 的前缀传递:

模板

<div class="question">
    {{question}}
    <div class="checkboxes">
        <label class="checkbox-label">
            <input class="checkbox" [(ngModel)]="checked.yes" (ngModelChange)="checkboxChanged('yes')" type="checkbox" [id]="index+'yes'"/>
            <label [for]="index+'yes'" class="custom-checkbox"></label>
        </label>
        <label class="checkbox-label">
            <input class="checkbox" [(ngModel)]="checked.no" (ngModelChange)="checkboxChanged('no')" type="checkbox" [id]="index+'no'"/>
            <label [for]="index+'no'" class="custom-checkbox"></label>
        </label>
    </div>
</div>

父组件

<div *ngFor="let question of questions;let index = index">
  <app-question [question]="question" [index]="index"></app-question>
</div>

demo