我正在开发一个小测验应用程序,为一个给定的问题有4个选项。我已经写了一个函数来验证单击的选项是正确的还是错误的,我在知道哪个选项是由用户选择的方面有问题,我想使用CSS作为样式--如果选择了错误的选项,单击的选项会变成红色,正确的选项将变成绿色,反之亦然。
HTML:
<div *ngFor="let actiVar of activeArray ;let j = index" >
{{actiVar.QuestionID}}.{{actiVar.Question}}
<br>
<br>
<button type="button" name="s" id="one" (click)="filterAnswer(actiVar.OP[j+0]) ; getColor(actiVar.OP[j+0])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+0]}}</button>
<br>
<br>
<button type="button" name="s" id="two" (click)="filterAnswer(actiVar.OP[j+1]) ; getColor(actiVar.OP[j+1])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+1]}}</button> <br>
<br>
<button type="button" name="s" id="three" (click)="filterAnswer(actiVar.OP[j+2]) ; getColor(actiVar.OP[j+2])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+2]}}</button> <br>
<br>
<button type="button" name="s" id="four" (click)="filterAnswer(actiVar.OP[j+3]) ; getColor(actiVar.OP[j+3])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+3]}}</button>
<br>
</div>我已经设置了对所选选项的getColor func单击,但是它所做的是,如果用户选择了一个错误的选项,它会将所有的4个选项都变成红色,而versa.It并没有具体地将单击的选项转换为红色。
getColor(j: any) {
if (j == this.activeArray[0].isRight) {
this.buttonColor = 'green';
}
else {
this.buttonColor = 'red';
}
}this.activeArray[0].isRight是从JSON中检索到的正确答案。我知道我必须使用按钮上的单个id标记来知道单击了哪个选项-按钮,但是我没有运气在堆栈溢出上找到正确的逻辑。
发布于 2018-05-04 10:39:02
您可以使用Template reference variables -> https://angular.io/guide/template-syntax#ref-vars
<button #buttonRef1 type="button" (click)="filterAnswer(actiVar.OP[j+0], buttonRef1)" [disabled]="permissionoptions">{{actiVar.OP[j+0]}}</button>
<button #buttonRef2 type="button" (click)="filterAnswer(actiVar.OP[j+1], buttonRef2)" [disabled]="permissionoptions">{{actiVar.OP[j+1]}}</button>
<button #buttonRef3 type="button" (click)="filterAnswer(actiVar.OP[j+2], buttonRef3)" [disabled]="permissionoptions">{{actiVar.OP[j+2]}}</button>
<button #buttonRef4 type="button" (click)="filterAnswer(actiVar.OP[j+3], buttonRef4)" [disabled]="permissionoptions">{{actiVar.OP[j+3]}}</button>filterAnswer:
filterAnswer(answer: string, button: HTMLButtonElement) {
// Do logic here
button.style.backgroundColor = desiredColor; // example: "#f00"
}发布于 2018-05-04 07:41:26
您可以使用自己的filterAnswer方法传递按钮的名称。这是一种比较容易的方法。
<button type="button" name="s" id="one" (click)="filterAnswer(actiVar.OP[j+0], 'one') ; getColor(actiVar.OP[j+0])" [ngStyle]="{backgroundColor: buttonColor}" [disabled]="permissionoptions">{{actiVar.OP[j+0]}}</button>发布于 2018-05-04 07:42:25
https://stackoverflow.com/questions/50169613
复制相似问题