根据json文件创建动态表单(首次创建表单后,可以通过单击按钮更改json文件)

时间:2019-06-21 15:27:55

标签: json angular dynamicform

我正在尝试基于https://angular.io/guide/dynamic-form创建动态表单。我正在使用json文件创建动态表单。我有2个json文件(sbb.json,gx.json)。当我第一次从json文件读取并创建表单时,它可以完美运行。但是我有一个按钮(Sbb),它将文件从gx.json更改为sbb.json。但是当我单击此按钮时,出现以下错误。

  

错误TypeError:“ this.form.controls [this.question.key]未定义

但是当我单击按钮“ Gx”时,它会正确创建表格而不会出现错误。

代码:

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;
  }

}

动态形式组件:

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);
  }
}

动态表单问题组件:

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>

1 个答案:

答案 0 :(得分:0)

为解决此问题,我在动态表单组件中添加了ngOnChanges()方法。

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));
  }
}