5

I have a list of questions with answer options as radio button field. I'm getting these questions and answers from JSON file.so am iterating over it on HTML and assigning values to formControlName dynamically. My problem is how to validate while iterating over control values?

*ngIf="cricketForm.control.get('ques{{i}}').invalid" 

*ngIf="cricketForm.control.get('ques{{i}}').invalid" 

this gives me an error. How to do it in the correct way?

https://stackblitz.com/edit/angular-yq4lyz-zt9b3h?file=app/form-field-overview-example.html Right now validation is not working correctly

html file:

<form [formGroup]="cricketForm">
  <div *ngFor = "let user of userJson; let i =index ">
    <div class="label1" for="NameId">{{user.question}}</div>
    <mat-radio-group formControlName="ques{{i+1}}" aria-label="Select an option">
      <div *ngFor = "let option of user.options; let j =index">
        <mat-radio-button  [value]=j>{{option}}</mat-radio-button>
      </div>
    </mat-radio-group>


  <div class="invalid-feedback" *ngIf="cricketForm.control.get('ques{{i}}').invalid" >This field is required</div>
  </div>
    <button (click)="onSubmit()">Submit</button>
    <button (click)="onReset()">Reset</button>
</form>

ts file:

ngOnInit() {
    this.cricketForm = this.formBuilder.group({
      ques1: [null, [Validators.required]],
      ques2: [null, [Validators.required]],
      ques3: [null, [Validators.required]],
      ques4: [null, [Validators.required]]
    })
    this.userDataService.getJSON().subscribe(data => {
      console.log(data);
      this.userJson = data;
      this.options = data.options
    });
}

Sample JSON Data:

[
{"question": "Who Was The First Indian To Hit A Test Century?", "options":["Lala Amarnath","Kapil Dev", "Sunil Gavaskar"],"ans":"Lala Amarnath"},
{"question":"Who Won The Inaugural Asia Cup Championship?","options":["Pakistan","Sri Lanka", "India"],"ans":"India"},
{"question":"Who Was Australia’s First Captain?","options":["F.S.Jackson"
,"D.W. Gregory", "Tony Lewis"],"ans":"D.W. Gregory"},
{"question":" When And Where Was The First Ranji Trophy Match Played?","options":["kolkata"
,"Mumbai", "Chennai"],"ans":"Chennai"}
]
10
  • Can you provide JSON data Commented Jun 1, 2019 at 5:52
  • 1
    Take a look at my library ngx-ez that does all the heavy lifting for form validation. github.com/adriandavidbrand/ngx-ez and a demo at stackblitz.com/edit/angular-pytks5 Commented Jun 1, 2019 at 5:55
  • @Sonam Is there only four questions every time? Commented Jun 1, 2019 at 6:40
  • @PrashantPimpale I'm doing for four questions.If questions no gets increased then I've to increase the form control in the ts file.Do you have better solution for this as well? Commented Jun 1, 2019 at 6:45
  • Create Dynamic Forms Commented Jun 1, 2019 at 6:51

1 Answer 1

3

You has a syntax error. Must be

*ngIf="cricketForm.get('ques'+(i+1)).invalid"

See your forked stackblitz

NOTE: I think you must try rethinking your code using FormArrays. The way is so simple as

<form formGroup="formArray">
  <div *ngFor = "let control of formArray.controls; let i =index ">
    <div class="label1" for="NameId">{{userJson[i].question}}</div>
    <mat-radio-group [formControl]="control" aria-label="Select an option">
      <div *ngFor = "let option of userJson[i].options; let j =index">
        <mat-radio-button  [value]=j>{{option}}</mat-radio-button>
      </div>
    </mat-radio-group>
  <div class="invalid-feedback" *ngIf="control.invalid" >This field is required</div>
  </div>
    <button (click)="onSubmit()">Submit</button>
    <button (click)="onReset()">Reset</button>

</form>

See that, we iterate over formArray.controls and use i=index. To show the labels use userJson[i]

where:

this.formArray=new FormArray(
    this.userJson.map(
      ()=>new FormControl(null,Validators.required))
);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Eliseo! I'll definitely apply your suggestion of using FormArray
1 for form array!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.