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

问题描述 投票:1回答:1

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

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

这是我的代码:

呈现问题列表:

<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

angular ngfor
1个回答
1
投票

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

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


1
投票

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

检查此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>
© www.soinside.com 2019 - 2024. All rights reserved.