Instead of using the selectedChoice
property for all the checks, you can bind the answer to the questions[index].answer
.
Please take a look at this working plunker
This is the result:
As you can see in that plunker, I'm binding the answer to the question.answer
directly:
<ion-list radio-group [(ngModel)]="question.answer">
<ion-item no-lines no-padding *ngFor="let choice of question.choices">
<ion-label>{{ choice.choiceText }}</ion-label>
<ion-radio [value]="choice"></ion-radio>
</ion-item>
</ion-list>
Please also notice that I'm using a slider to add a nice effect when changing the questions.
View code
<ion-content padding>
<ion-slides>
<ion-slide *ngFor="let question of questions; let i = index">
<h1>{{ question.text }}</h1>
<ion-list radio-group [(ngModel)]="question.answer">
<ion-item no-lines no-padding *ngFor="let choice of question.choices">
<ion-label>{{ choice.choiceText }}</ion-label>
<ion-radio [value]="choice"></ion-radio>
</ion-item>
</ion-list>
<span style="font-size: 1.2rem;">Selected answer: {{ question.answer | json }}</span>
<ion-row margin-top>
<ion-col>
<button (click)="showPrevious()" ion-button text-only [disabled]="i === 0" >Previous</button>
</ion-col>
<ion-col>
<button [disabled]="!question.answer" *ngIf="i < questions.length - 1" (click)="showNext()" ion-button text-only >Next</button>
<button [disabled]="!question.answer" *ngIf="i === questions.length - 1" (click)="showNext()" ion-button text-only >Submit</button>
</ion-col>
</ion-row>
</ion-slide>
</ion-slides>
</ion-content>
Component code
import { Component, ViewChild } from '@angular/core';
import { NavController, Content, Slides } from 'ionic-angular';
@Component({...})
export class HomePage {
@ViewChild(Slides) slides: Slides;
public questions: Array<{ text: string, answer: number, choices: Array<{choiceId: number, choiceText: string}> }>
ngOnInit() {
this.slides.lockSwipes(true);
}
constructor() {
this.questions = [
{
text: 'Question 1',
choices: [
{
choiceId: 1,
choiceText: 'Choice 1-1'
},
{
choiceId: 2,
choiceText: 'Choice 1-2'
},
{
choiceId: 3,
choiceText: 'Choice 1-3'
},
{
choiceId: 4,
choiceText: 'Choice 1-4'
}
],
answer: null
},
{
text: 'Question 2',
choices: [
{
choiceId: 21,
choiceText: 'Choice 2-1'
},
{
choiceId: 22,
choiceText: 'Choice 2-2'
},
{
choiceId: 23,
choiceText: 'Choice 2-3'
},
{
choiceId: 24,
choiceText: 'Choice 2-4'
},
],
answer: null
},
{
text: 'Question 3',
choices: [
{
choiceId: 31,
choiceText: 'Choice 3-1'
},
{
choiceId: 32,
choiceText: 'Choice 3-2'
},
{
choiceId: 33,
choiceText: 'Choice 3-3'
},
{
choiceId: 34,
choiceText: 'Choice 3-4'
},
],
answer: null
}
]
}
public showPrevious(): void {
this.slides.lockSwipes(false);
this.slides.slidePrev(500);
this.slides.lockSwipes(true);
}
public showNext(): void {
this.slides.lockSwipes(false);
this.slides.slideNext(500);
this.slides.lockSwipes(true);
}
}