Search code examples
ionic2angular-ngmodelangular2-directivesradiobuttonlistngfor

Angular2,Ionic2: How to do 2way binding for radio button in nested *ngfor using ngModel?


I've my API in JSON in the following format.

enter image description here

I want to display this in the form of question & choices format. I'm trying to display the choices using radio buttons. But my ngModel is not working. I want to access the whole object of the selected choice using ngModel in my .ts file.

Here is my ts code

export class Quiz implements OnInit {
    testcontents: Array<any>=[];
    choiceObj:any;

 constructor(public navCtrl: NavController, public navParams: NavParams,public http:Http) {}
     ngOnInit()
     {
       this.launchfunc();
     }
     launchfunc()
     {
    this.http.post('launchtest/getTestContent',this.launchtestobj).subscribe(resp=>{
         this.testcontents = resp.data.questions;
    });
     }

    selectChoice($event)
    {
      console.log("12312341234",event);
      console.log("obj",this.choiceObj);
    }

Here is my html code

<ion-content padding>
<div *ngFor="let qContent of testcontents; let i = index">
    {{i+1}} {{qContent.questionText}}
    <div *ngFor="let choiceObj of qContent.choice">
        <input name='options' type='radio' [value]='choiceObj' [(ngModel)]='choiceObj.choice' (ngModelChange)="selectChoice(choiceObj)" />
        <label [for]='choiceObj'>{{choiceObj.choiceText}}</label>
    </div>
</div>

This is the output for the above code.enter image description here I don't understand why is obj undefined. I've a problem with the ngModel. I'm not understanding what should I put my ngModel as and how should I access the "choiceObj" in typescript file.Can someone please help me.


Solution

  • the model is choiceObj.choice which is not exist in object of choice. you need to replace it with 'choiceObj.choiceId'

    <ion-content padding>
    <div *ngFor="let qContent of testcontents; let i = index">
        {{i+1}} {{qContent.questionText}}
        <div *ngFor="let choiceObj of qContent.choice">
            <input name='options' type='radio' [value]='choiceObj' [(ngModel)]='choiceObj.choiceId' (ngModelChange)="selectChoice(choiceObj)" />
            <label [for]='choiceObj'>{{choiceObj.choiceText}}</label>
        </div>
    </div>