I'm creating a quiz app and need to toggle between mat-checkbox or mat-radio-button, depending on whether the question has one or more answers. Question #1 is a single choice answer question and shows with mat-radio-button whereas Question #2 is a multiple answer question but is also displaying with mat-radio-button instead of mat-checkbox.
This is how my template looks like:
<form [formGroup]="formGroup">
<ol *ngIf="multipleAnswer === false">
// using mat-radio-buttons here
</ol>
<ol *ngIf="multipleAnswer === true">
// using mat-checkboxes here
</ol>
</form>
and in my ts file the logic looks like:
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;
}
}
}
don't need shuffledAnswers, question type should be inferred from the assets/quiz.ts file (shouldn't need to hard code the question type), and answers should be numbers, not strings
in my QuizService:
getQuestionType(): boolean {
return (this.correctAnswers && this.correctAnswers.length === 1);
}
multipleAnsweronly once, insidengOnInit. Did you try to check it inngOnChanges?