我正在使用ngFor提出问题,在那些问题中,我正在使用另一个ngFor来显示每个答案旁边的单选按钮的posibble答案。
一切都是正确生成的,如果我在第一个问题中点击任何答案的收音机,一切顺利。
当我尝试点击第二个问题的答案时,问题就出现了,如果我点击其中任何一个问题,就会检查第一个问题的单选按钮。
这是我现在的代码。
<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链接到答案的属性,因此在方法中我将all设置为false,然后将所需的一个设置为true。
您需要考虑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);
}
说实话,我不知道为什么这解决了它,但我刚改变了这一行:
<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)">
现在它工作得很好,我可以点击两个问题的单选按钮。
刚想通了,我用嵌套ngfor的索引设置每个无线电的id,但是它重复了每个新问题,因为嵌套的ngfor的索引再次从0开始。因此为什么使用每个答案的id立即工作。