Search code examples
jsonangulardynamicform

Create dynamic form based on json file (json file can be changed by button click after first creation of form)


I am trying to create a dynamic form based on https://angular.io/guide/dynamic-form. I'm using a json file to create dynamic form. i am having 2 json files (sbb.json , gx.json). The first time when I read from json file and create the form, it works perfectly. But I have a button (Sbb) which changes file from gx.json to sbb.json . but when i click this it gives me following error.

ERROR TypeError: "this.form.controls[this.question.key] is undefined

but when i click on button "Gx" it agian creates the form properly without an error.

Code:

app.component.ts:

import { Component } from '@angular/core';
import SbbData from './sbb.json';
import GxData from './gx.json';
@Component({
  selector: 'app-root',
  template: `
    <div>
    <button type="button" (click)="callSbb()">SBB</button> 
    <button type="button" (click)="callGx()">GX</button> 
      <app-dynamic-form [questions]="questions"></app-dynamic-form>
    </div>
  `,
  providers: []
})
export class AppComponent{


  questions: any[];
  constructor() {
    this.questions = GxData;
  }

  callGx() {
    this.questions = GxData;

  }
  callSbb() {
    this.questions = SbbData;
  }

}

dynamic-form component:

import { Component, Input, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { QuestionControlService } from '../question-control.service';

@Component({
  selector: 'app-dynamic-form',
  templateUrl: './dynamic-form.component.html',
  providers: [QuestionControlService]
})
export class DynamicFormComponent implements OnInit {

  @Input() questions: any[] = [];
  form: FormGroup;
  payLoad = '';

  constructor(private qcs: QuestionControlService) { }

  ngOnInit() {
    this.form = this.qcs.toFormGroup(this.questions);
  }

  onSubmit() {
    this.payLoad = JSON.stringify(this.form.value);
  }
}

dynamic-form-component.html:

<form (ngSubmit)="onSubmit()" [formGroup]="form">

    <div *ngFor="let question of questions" class="form-row">
      <app-question [question]="question" [form]="form"></app-question>
    </div>

    <div class="form-row">
      <button type="submit" [disabled]="!form.valid">Save</button>
    </div>
</form>

question-control.service:

import { Injectable } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

@Injectable()
export class QuestionControlService {
  constructor() { }

  toFormGroup(questions: any[]) {
    let group: any = {};

    questions.forEach(question => {
      group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
        : new FormControl(question.value || '');
    });
    return new FormGroup(group);
  }
}

dynamic-form-question component:

import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';

@Component({
  selector: 'app-question',
  templateUrl: './dynamic-form-question.component.html'
})
export class DynamicFormQuestionComponent {
  @Input() question: any;
  @Input() form: FormGroup;
  get isValid() { return this.form.controls[this.question.key].valid; }
}

dynamic-form-question component.html:

<div [formGroup]="form">

  <div [ngSwitch]="question.controlType" class="checkbox_wrapper">

    <input *ngSwitchCase="'textbox'" [formControlName]="question.key" [id]="question.key" [type]="question.type" name="question.name">
    <label [attr.for]="question.key">{{question.label}}</label>
    <div *ngIf="question.child =='dropdown'" [formGroupName]="question.key">
      <select  [id]="question.key2"   >
        <option *ngFor="let opt of question.options" [attr.value]="opt.key" [attr.selected]="opt.select">{{opt.value}}</option>
      </select>
    </div>

    <select [id]="question.key" *ngSwitchCase="'dropdown'" [formControlName]="question.key" >
      <option *ngFor="let opt of question.options" [attr.value]="opt.key" [attr.selected]="opt.select">{{opt.value}}</option>
    </select>
    <!-- <label [attr.for]="question.key">{{question.label}}</label> -->
  </div>


  <div class="errorMessage" *ngIf="!isValid">{{question.label}} is required</div>
</div>

Solution

  • To solve this problem i added ngOnChanges() method in dynamic-form component.

    import { Component, Input, OnInit, SimpleChanges } from '@angular/core';
    import { FormGroup } from '@angular/forms';
    import { QuestionControlService } from '../question-control.service';
    
    @Component({
      selector: 'app-dynamic-form',
      templateUrl: './dynamic-form.component.html',
      providers: [QuestionControlService]
    })
    export class DynamicFormComponent implements OnInit {
    
      @Input() questions: any[] = [];
      form: FormGroup;
      payLoad = '';
    
    //newly added function
    
      ngOnChanges(changes: SimpleChanges) {
        for (let propName in changes) {
          let change = changes[propName];
          // let curVal = JSON.stringify(change.currentValue);
          // let prevVal = JSON.stringify(change.previousValue);
          if (propName === 'questions') {
            this.form = this.qcs.toFormGroup(this.questions);
          }
        }
      }
      constructor(private qcs: QuestionControlService) { }
    
      ngOnInit() {
        this.form = this.qcs.toFormGroup(this.questions);
      }
    
      onSubmit() {
        this.payLoad = JSON.stringify(this.form.value);
        console.log(JSON.parse(this.payLoad));
      }
    }