简体   繁体   中英

How to validate dynamic radio button in ionic 3

I have a series of questions which have radio answer choices. I can't figure out how to use angular validation to require the user to select all answer before clicking save & next.

NOTE: Please note that click save & next button gets the next 5 question from the controller depending on what choice was made. It's basically a dynamic questionnaire. Below is my code.

<ion-content id="testmodeCont" >
 <div class="midCont mrgn0" >
   <form #f="ngForm" class="login">
       <div class="formCont">
         <div *ngIf = "questionCategory == 'Diabetes'">
           <div class="boxInCont" *ngFor="let question of AllQuestions | slice:numberOfQuestionsToDisplay:numberOfQuestionsToleft; let i = index">
            <div *ngIf="mLanguageFlag === 'English'" >
              <div class="heading" *ngIf="question.QuestionType=='dropdown'||question.QuestionType=='radio'||question.QuestionType=='toggle'|| question.QuestionType=='multiselect' ">
                Q.&nbsp;{{question.QuestionText}}
                </div>
            </div>

          <div *ngIf="mLanguageFlag === 'English'">
            <div class="row mrgnB20"  *ngIf="question.QuestionType=='radio'">
             <div>
               <div class="quetxt">                       
                <ion-list radio-group  [ngModelOptions]="{standalone: true}" [(ngModel)]="AllGroupAnswers[i].ExpectedAnswerId" >
                                     <ion-item  class="opteach" *ngFor="let answer of question.ExpectedAnswers">
                  <ion-label class="radioBox fr">{{answer.Answer}}
                  </ion-label>
                <ion-radio item-left  [value]="answer.ExpectedAnswerId" (ionSelect)="ValueChanged(answer)">
                  </ion-radio>
                 </ion-item>
                </ion-list>                    
               </div>
             </div>
            </div>
          </div>

          <div *ngIf="mLanguageFlag === 'English'">
                 <ion-item class="row" *ngIf="question.QuestionType=='dropdown'">
                   <ion-select formControlName="option" okText="Okay" cancelText="Nah" placeholder= "{{'personal.select'|translate}}" interface = "alert">
                     <ion-option *ngFor="let answer of question.ExpectedAnswers" [value]="answer.Answer" (ionSelect)="ValueChanged(answer)">{{answer.Answer}}
                 </ion-option>
                   </ion-select>
                 </ion-item>
             </div>
        </div>
      </div>
    </div> 
    </form>                 
  </div>
  <div class ="testbtn">
    <ion-grid>
      <ion-row>
       <ion-col align-self-center>
        <button ion-button  block color="button-color" class="prevBtn" type="submit" (click) = "previous()" *ngIf="previousState" >{{"Previous" | translate}}</button>
       </ion-col>
       <ion-col align-self-end>
        <button ion-button block color="button-color"  class="saveBtn" type="submit" (click) = "next()" *ngIf="isDataLoad" >{{"Save & Next" | translate}}</button>
       </ion-col>
      </ion-row>
    </ion-grid>
      </div>          

ts file

    import { Component } from '@angular/core';
    import { NavController, NavParams, AlertController, ToastController } from 'ionic-angular';
    import { UserService } from '../../providers/service/share';
    import { Service } from '../../providers/service/service';
    import { Functions } from '../../providers/service/functions';
    import { Values } from '../../providers/service/values';
    import { UtilService } from '../../providers/service/util';
    import { FeedsPage } from '../feeds/feeds';
    import { TestPage } from '../test/test';

    @Component({
      templateUrl: 'testmode.html',
    })
    export class TestmodePage {
      questionCategory: any
      ckeckedArray: any;
      answersID: any;
      userPrefernce: any;  
      AllQuestions: any;
      edittest: any;
      testQuestionList: any;
      TestQuestions: any;
      lifestyleAnswers: any;
      AllGroupAnswers: any;
      AllTestAnswer: any;
      ShowlifeStyleSave: boolean = false;
      ExpectedAnswers: any;
      mLanguageSelect: any;
      mLanguageClass: any;
      mLanguageFlag: any;
      mLanguageClassdisc: any;
      mLanguageClassWhite: any;
      mLanguageClassGreen: any;
      success: any;
      numberOfQuestionsToDisplay: any;
      numberOfQuestionsToleft: any 
      previousState: boolean = false;
      isDataLoad: boolean = false;
      pageIndex: any;
      testform: FormGroup;
      constructor(public navCtrl: NavController,public alertCtrl: AlertController,private toastCtrl: ToastController, public navParams: NavParams, public functions: Functions, public values: Values, public utilServices: UtilService, public userService: UserService, public service: Service) {  

      this.numberOfQuestionsToDisplay = 0; 
      this.numberOfQuestionsToleft = 5;
      this.questionCategory = this.navParams.get('questionCategory')
      this.mLanguageFlag = 'English';
      this.testQuestionList = [];
      this.TestQuestions = [];
      this.lifestyleAnswers = [];
      this.AllGroupAnswers = [];
      this.AllTestAnswer = [];
      this.ExpectedAnswers = [];
      this.AllQuestions = [];
      this.pageIndex = 0 ;
      console.log(this.questionCategory);
      this.setTestInfo();
      }

      ionViewDidLoad(){
         this.mLanguageSelect = this.userService.getLocaleDisplayName();
              console.log(this.mLanguageSelect)
              if(this.mLanguageSelect == 'english'){
                              this.mLanguageClass = ' ';
                              this.mLanguageFlag='English';
                              this.mLanguageClassWhite = ' ';
                              this.mLanguageClassGreen = ' ';
                            }else if(this.mLanguageSelect == 'hindi'){
                              this.mLanguageClass = 'heading2';
                              this.mLanguageClassWhite = 'heading3';
                              this.mLanguageFlag='Hindi';
                              this.mLanguageClassGreen = 'heading4';
                            }
      }

       setTestInfo(){
            var url = '/api/JM_TestQuestions?userId=1002&questionCategory='+ this.questionCategory ;
            this.service.jivaGetMethod('1234567899','mobile',url).then((results) => {
            console.log(results);          
            this.userService.setLifeStyleInfo(results);              
            this.edittest = this.userService.getLifeStyleInfo();
            console.log("Your question",this.edittest);
            this.AllQuestions = this.edittest.TestQuestions;
            console.log("Your answer", this.AllQuestions);
             for (var i = 0; i < this.AllQuestions.length; i++) {

                    // console.log("hello", this.AllQuestions[i]);
                    var obj= this.AllQuestions[i]
                        this.AllTestAnswer[i] = obj.ExpectedAnswers;
                        console.log(this.AllTestAnswer[i]+ i);
                        this.TestQuestions.push(obj);
                        console.log(this.TestQuestions.push(obj));
                        if (obj.ExpectedAnswers[0].UserAnswer==true){
                          this.AllGroupAnswers.push(obj.ExpectedAnswers[0]);
                        }else if(obj.ExpectedAnswers[1].UserAnswer==true){
                          this.AllGroupAnswers.push(obj.ExpectedAnswers[1]);
                        }else {
                          this.AllGroupAnswers.push({});
                        }
                     console.log("working");
                     this.testQuestionList.push(obj);
                     this.isDataLoad = true;
                }
                  })
                  .catch((error)=>{
                    console.log(error);
          })
      }

    ValueChanged(answer){
        console.log(answer);
        console.log(this.AllQuestions)  ; 
        for (var i = 0; i < this.AllQuestions.length; i++) {
          if (this.AllQuestions[i].QuestionId==answer.QuestionId) {
            for (var j = 0; j < this.AllQuestions[i].ExpectedAnswers.length; j++) {
              console.log(this.AllQuestions[i].ExpectedAnswers[j].Answer);
              if (this.AllQuestions[i].ExpectedAnswers[j].ExpectedAnswerId==answer.ExpectedAnswerId) {            
                console.log('match-->',this.AllQuestions[i].ExpectedAnswers[j].ExpectedAnswerId,'-------',answer.ExpectedAnswerId);
                this.AllQuestions[i].ExpectedAnswers[j].UserAnswer=true;
                console.log(this.AllQuestions[i].ExpectedAnswers[j]);
               }else {
                console.log('not match-->',this.AllQuestions[i].ExpectedAnswers[j].ExpectedAnswerId,'-------',answer.ExpectedAnswerId);
                this.AllQuestions[i].ExpectedAnswers[j].UserAnswer=false;
              }
            }
            break;
          }
        }
      }

      submitTest(){
            console.log(this.testQuestionList);
            var TestQuestions = this.testQuestionList ;
                  var testData =  {
                   "User": {
                            "UserId": 79163,
                            "FirstName": null,
                            "LastName": null,
                            "MobileNo": null,
                            "EmailId": null,
                            "UserSfdcId": null,
                            "FacebookId": null,
                            "GooglePlusId": null,
                            "AccessToken": null,
                            "AuthType": null,
                            "UserLanguage": null,
                            "UserDeviceId": null,
                            "UserPersonalDetails": null,
                            "CountryCode": 0
                        },
                    "TestQuestions": TestQuestions
            };
            this.functions.presentLoading(this.values.lan.WaitTitle);
            // var identity = this.userService.getUserIdentity();
            //  var authtype = this.userService.getUserData().AuthType;
             var url = 'http:///api/JM_TestQuestions';
             this.service.submitSetUser1('1234567899','mobile',url,JSON.stringify(testData)).then((results) => {
              console.log(results);
              this.success = results
              console.log(this.success);
              this.functions.dismissLoading();

                        //this.navCtrl.setRoot(TestresultsPage);

            }) .catch((error)=> {
              alert("Please try after sometime..");
               this.functions.dismissLoading();
            })
          }
    next(){
       this.previousState = true;
       console.log(this.AllQuestions.length)
       console.log(this.numberOfQuestionsToleft)
         if(this.AllQuestions.length > this.numberOfQuestionsToleft) { 
          this.pageIndex++; 
          console.log(this.pageIndex)      
          this.numberOfQuestionsToDisplay = this.numberOfQuestionsToDisplay +5; 
          this.numberOfQuestionsToleft = this.numberOfQuestionsToleft + 5;
          console.log(this.numberOfQuestionsToDisplay);
          console.log(this.numberOfQuestionsToleft);
          this.submitTest();
         } else  {
          this.submitTest();
          let toast = this.toastCtrl.create({
              message: 'Your answer for ' + this.questionCategory + ' test was saved successfully',
              duration: 2000,
              position: 'top'
            });
            toast.onDidDismiss(() => {
              console.log('Dismissed toast');
            });
            toast.present();
          this.navCtrl.setRoot(FeedsPage);
      }
    }
  previous() {
        this.pageIndex--;
        console.log(this.pageIndex)
        this.numberOfQuestionsToDisplay = this.numberOfQuestionsToDisplay - 5; 
          this.numberOfQuestionsToleft = this.numberOfQuestionsToleft - 5;
          console.log(this.numberOfQuestionsToDisplay);
          console.log(this.numberOfQuestionsToleft);
          this.submitTest();
        if(this.pageIndex == 0){
          console.log(this.pageIndex)
          this.previousState = false;
        }
      }
   ionViewWillLeave(){
          let alert = this.alertCtrl.create({
          title: "Jiva Ayurveda",
          message: "Do you want to close the test ?",
          buttons:[
            {
              text:"Yes",
              handler: () => {
                this.navCtrl.setRoot(TestPage);        
              }
            },
            {
              text:"No",
              handler: () => {
            }
          }
          ]      
      });
      alert.present();
   }
}

You can use a (click)=function(arg1, arg2) in order to create a function to check the specific validation you need to see happening.

Edit:

In the function you call with (click) add a logic at the beginning:

function(arg1) {
  if(!arg1){
    return; // eventually output a string in an error message to indicate the user needs to input or tick a box
  } else {
    // next page
  }
}

use formgroup and initialize form like

this.loginForm = this.fb.group({
 username: ['', Validators.required],
 password: ['', Validators.required]
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM