嵌套ngFor select不可点击

时间:2019-03-17 21:52:20

标签: angular ngfor

我正在使用ngFor提出问题,在这些问题中,我正在使用另一个ngFor显示每个答案旁边带有单选按钮的斜体答案。

一切都正确生成,如果我在第一个问题中单击任何答案的广播,一切都会顺利进行。

当我尝试单击第二个问题的答案时,问题就来了,如果我单击其中任何一个,则会选中第一个问题的单选按钮。

这是我现在拥有的代码。

<div id="question{{questionInd}}" class="card bg-blue-grey bg-lighten-5" *ngFor="let question of focusGroup.aptitudeTest.questions; let questionInd = index">
    <div class="card-header"><span class="text-bold-500 primary">¿{{question.question}}?</span></div>
    <div class="card-body">
        <div class="card-block">
            <div *ngFor="let answer of question.answers; let answerInd = index" class="custom-control custom-radio custom-control-inline">
                <input type="radio" id="answer{{answerInd}}" [value]="answer.answer" name="desiredAnswerRadio{{questionInd}}" class="custom-control-input" (change)="desiredAnswer(question, answer)">
                <label class="custom-control-label" for="answer{{answerInd}}">
                    <span class="display-block"><i class="ft-minus"></i> {{answer.answer}}</span>
                </label>
            </div>
        </div>
    </div>
</div>

以下图片是我以前解释的直观指南。

Questions and answers displayed

This happened when I clicked the answer Yes

This happened when I clicked the answer Certainly not

编辑:

根据请求,这是 desiredAnswer 方法。

desiredAnswer(question: ITestQuestion, desiredAnswer: ITestAnswerOption) {
    question.answers.forEach(function(answer: ITestAnswerOption) {
        answer.desired = false;
    });
    desiredAnswer.desired = true;
    console.log(question.answers);
}

由于我只需要一个答案,并且每个单选按钮都使用 ngModel 链接到答案的属性,因此在该方法中,我将全部设置为false,然后将想要一个 true

2 个答案:

答案 0 :(得分:0)

您需要考虑javascript对象范围。在desiredAnswer函数question.answers.forEach(function(answer: ITestAnswerOption) {中,answer: ITestAnswerOption对象与您传递给该函数以设置desiredAnswer.desired = true;的对象不同,因此该函数应如下所示

desiredAnswer(question: ITestQuestion, desiredAnswer: ITestAnswerOption) {
  question.answers.forEach(function(answer: ITestAnswerOption) {
    if (desiredAnswer == answer) answer.desired = true;
    else answer.desired = false;
  });
  console.log(question.answers);
}

答案 1 :(得分:0)

说实话,我不知道为什么能解决这个问题,但我只是更改了这一行:

<input type="radio" id="answer{{answerInd}}" [value]="answer.answer" name="desiredAnswerRadio{{questionInd}}" class="custom-control-input" (change)="desiredAnswer(question, answer)">

对此:

<input type="radio" id="answer{{answer.id}}" name="desiredAnswerRadio{{question.id}}" class="custom-control-input" (change)="desiredAnswer(question, answer)">

现在它可以正常工作了,我可以单击两个问题的单选按钮。

Both questions answered

弄清楚了,我用嵌套ngfor的索引设置了每个无线电的ID,但是由于嵌套ngfor的索引再次从0开始,所以它重复了每个新问题。 因此,为什么要立即使用每个答案的ID。