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

问题描述 投票:3回答:4

我正在列出问题列表(问题的名称和是/否复选框)

问题是,当我单击第二个问题复选框时,它仍会更改第一个问题的复选框。

这是我的代码:

呈现问题列表:

<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}}”,它可以正常工作。谢谢大家的帮助。

angular ngfor
4个回答
3
投票

到目前为止,我只发现您有一个与label for attributeinput 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 🚀


2
投票

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

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


2
投票

如果您有一个带有是/否答案的问题列表,建议您使用单选按钮。

检查此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>

1
投票

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

.checkbox {
    opacity: 0;
}
.checkbox-label{
    position: relative;
}
© www.soinside.com 2019 - 2024. All rights reserved.