我正在创建一个测验应用,需要根据问题是否具有一个或多个答案,在mat-复选框或mat-单选按钮之间切换。问题1是单选题,并带有mat-radio-button显示,而问题#2是多选题,但也具有mat-radio-button而非mat-checkbox的显示。
这是我的模板的样子:
<form [formGroup]="formGroup">
<ol *ngIf="multipleAnswer === false">
// using mat-radio-buttons here
</ol>
<ol *ngIf="multipleAnswer === true">
// using mat-checkboxes here
</ol>
</form>
在我的ts文件中,逻辑看起来像:
multipleAnswer: boolean;
ngOnInit() {
this.multipleAnswer = this.quizService.getQuestionType();
}
ngOnChanges(changes: SimpleChanges) {
if (changes.question) {
switch (this.question.type) {
case 'SINGLE_CHOICE':
this.formGroup = new FormGroup({
answer: new FormControl([null, Validators.required])
});
break;
case 'MULTIPLE_CHOICE':
const multipleChoiceValidator = (control: AbstractControl) =>
control.value.reduce(
(valid: boolean, currentValue: boolean) => valid || currentValue
, false
) ? null : {answers: 'At least one answer needs to be checked!'};
this.formGroup = new FormGroup({
answers: this.formBuilder.array(this.question.shuffledAnswers
.map((answer: string) => this.formBuilder.control(false)),
multipleChoiceValidator
),
});
break;
}
}
}
不需要shuffledAnswers,应该从assets / quiz.ts文件中推断问题类型(不需要对问题类型进行硬编码),答案应该是数字,而不是字符串
在我的QuizService中:
getQuestionType(): boolean {
return (this.correctAnswers && this.correctAnswers.length === 1);
}
答案 0 :(得分:1)
有几个问题。首先,仅在multipleAnswer
内部调用ngOnInit
会在开始时只设置一次此布尔变量,它应该在ngOnChanges
内部。
但这不是唯一的问题,主要问题在您的QuizService
中。在这里,您使用this.quizService.getQuestionType();
方法将multipleAnswer
设置为true或false,但是在QuizService的getQuestionType()
方法内部,您正在检查this.correctAnswers
是否已设置并且元素长度为1但{{1 }}始终为空。
另一个问题是您的this.correctAnswers
中有ngOnChanges
,switch (this.question.type)
似乎从未定义过。
按如下所示编辑代码,并在每次出现问题时检查控制台输出。
添加新方法以从问题中获取this.question
。
correctAnswers
并按如下所示编辑ngOnChanges的开头,我还添加了一个控制台输出,以便您可以从上面的新方法中查看数据。
getCorrectAnswers(question:QuizQuestion){
return question.options.filter((item)=> item.correct);
}
由于您的代码背后有自己的逻辑,因此我无法修改所有代码,但是我更新了答案,以便在ngOnChanges中正确设置与此问题相关的变量。