Let me explain it in detail.Sorry for the question framing.
I've an array of Objects which is stored in the REST API. That array contains questions and choices. Each question has 4 choices which are radio buttons.
I'm trying to display one question at a time on the same page along with the choices of the question. I've 2 buttons "previous" and "forward" which load the question on the same page.
When I click the next button the next question in the array along with the choices are displayed.When I click previous button the previous question is being displayed but not "with the checked radio button". Now my requirement is that the radio button checked in the previous question has to remain checked even after going to next question and when I click previous it has to show me which radio button have I checked.
I'm trying to use [checked] option available with the radio button.But I'm not able to get it.Here is my code:
<div *ngIf="questions[indexVal]">
{{indexVal+1}} {{questions[indexVal].Text}}
<div *ngFor="let choiceObj of questions[indexVal].choices">
<input name='question' type='radio' [value]='choiceObj' [(ngModel)]='selectedchoice' (ngModelChange) = "storeChoice(choiceObj.choiceId,questions[indexVal])"
[checked]="check(questions[indexVal])"/>
<label [for]='choiceObj'> {{choiceObj.choiceText}} </label>
</span>
</div>
</div>
<button ion-button value="previous" (click)="PrevQues()" [disabled] =
"disableprev"> PREVIOUS </button>
<button ion-button value="next" (click)="NextQues()"> NEXT </button>
Initially the indexVal=0 which means it is pointing to the first question.On clicking the next button it becomes indexVal+=1 and for previous it becomes indexVal-=1;
here is my typescript code. I'm trying to maintain an array called "answers" which stores the selected choice.
storeChoice(choiceId, questions[indexVal])
{
questions[indexVal].answers[0] = choiceId;
}
check(questions[indexVal])
{
return questions[indexVal].answers[0];
}
Instead of using the
selectedChoice
property for all the checks, you can bind the answer to thequestions[index].answer
. Please take a look at this working plunkerThis is the result:
As you can see in that plunker, I'm binding the answer to the
question.answer
directly:Please also notice that I'm using a slider to add a nice effect when changing the questions.
View code
Component code
Your check function needs to return the boolean value which in your case doesn't. Please check below code:
And instead of making answers as an array, have it simple property and use it like below:
Hope it helps!!