我正在尝试将函数与ngClass一起使用,以将逻辑与模板分开,以使代码更易于维护,但最初使所有选项均从is-incorrect样式中突出显示红色。请在下面查看我的代码:
<mat-radio-button class="answer" [value]="option.optionValue" disableRipple="true"
[ngClass]="{'initial-state': initialState(),
'is-correct': isCorrect(),
'is-incorrect': isIncorrect()}">
</mat-radio-button>
initialState(): boolean {
return this.selectedRadioButtonOption === '';
}
isCorrect(): boolean {
return this.option === this.question.correctAnswer
&& this.selectedRadioButtonOption === this.question.correctAnswer;
}
isIncorrect(): boolean {
return this.option !== this.question.correctAnswer
&& this.selectedRadioButtonOption === this.option;
}
答案 0 :(得分:1)
在您的评论中,您说过您正在ngFor循环中创建单选按钮。因此,在HTML中,“选项”是指特定单选按钮的数据。在TS文件中,“选项”是其自己的变量,因此它永远不会更改。尝试将选项值发送到函数中。
所以看起来像这样
<mat-radio-button class="answer" [value]="option.optionValue" disableRipple="true"
[ngClass]="{'initial-state': initialState(),
'is-correct': isCorrect(option.optionValue),
'is-incorrect': isIncorrect(option.optionValue)}">
</mat-radio-button>
initialState(): boolean {
return this.selectedRadioButtonOption === '';
}
isCorrect(option): boolean {
return option === this.question.correctAnswer
&& this.selectedRadioButtonOption === option;
}
isIncorrect(option): boolean {
return option !== this.question.correctAnswer
&& this.selectedRadioButtonOption === option;
}