复选框值未以反应形式改变角度

时间:2019-06-27 13:59:37

标签: angular checkbox angular-reactive-forms

我可以在反应性Forms的帮助下从json文件生成表单。表单的生成可以正常工作,但是我面临的问题是-当我第一次在mozila中单击复选框时,其值变为“ on”。但是当我取消选中它时,没有任何反应,它的值仍然是“ On”,应该是“ off or false”。在chrome上单击没有任何反应。

app.components.ts

import { Component } from '@angular/core';
import { QuestionControlService } from './question-control.service';
import GxData from './gx.json';
@Component({
  selector: 'app-root',
  template: `
    <div>
      <app-dynamic-form [questions]="questions"></app-dynamic-form>
    </div>
  `,
  providers: []
})
export class AppComponent{

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

} 

dynamic-form.components.ts

import { Component, Input, OnInit, SimpleChanges } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { QuestionControlService } from '../question-control.service';
import SbbData from '../sbb.json';
import GxData from '../gx.json';

@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);
  }
  callGx() {
    this.questions = GxData;
    this.form = this.qcs.toFormGroup(this.questions);
  }
  callSbb() {
    this.questions = SbbData;
    this.form = this.qcs.toFormGroup(this.questions);
  }

  onSubmit() {

    this.payLoad = JSON.stringify(this.form.value);
    console.log(JSON.parse(this.payLoad));
  }

}

dynamic-form.component.html

<div class="search_box">
  <form (ngSubmit)="onSubmit()" [formGroup]="form">
      <button type="button" (click)="callSbb()">SBB</button> 
      <button type="button" (click)="callGx()">GX</button> 
    <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>

  <div *ngIf="payLoad" class="form-row">
    <strong>Saved the following values</strong><br>{{payLoad}}
  </div>
</div>
{{form.value |json}} 

question-control.service.ts

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.ts

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

// import { QuestionBase } from '../question-base';

@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>

    <select [id]="question.key" *ngSwitchCase="'dropdown'" [formControlName]="question.key" name = "{{question.name}}" >
      <option *ngFor="let opt of question.options" [attr.value]="opt.key" [selected]="opt.select">{{opt.value}}</option>
    </select>
  </div>
  <div class="errorMessage" *ngIf="!isValid">{{question.label}} is required</div>
</div> 

两个json文件都类似

[
    {
        "key": "Context",
        "label": "Context",
        "required": false,
        "order": 1,
        "controlType": "textbox",
        "name": "Context",
        "type": "checkbox"
    },
    {
        "key": "contextopt",
        "label": "",
        "required": false,
        "order": 2,
        "controlType": "dropdown",
        "name": "contextopt",
        "options": [
            {
                "key": "All Context",
                "value": "All Context",
                "select": true
            },
            {
                "key": "aaa",
                "value": "aaa"
            },
            {
                "key": "bb",
                "value": "bb"
            },
            {
                "key": "Other",
                "value": "Other"
            }
        ]
    },
    {
        "key": "Movement",
        "label": "Movement",
        "required": false,
        "order": 3,
        "controlType": "textbox",
        "name": "Movement",
        "type": "checkbox"
    }
]

1 个答案:

答案 0 :(得分:0)

更新,问题出在您写[type]="question.type"和question.type =“ checkbox”时。看起来Angular不喜欢此复选框(但喜欢使用电子邮件,电话号码...)

ng*SwitchCase="'textbox'"替换为

<ng-container *ngSwitchCase="'textbox'">
<input  *ngIf="question.type!='checkbox'" [formControlName]="question.key"
        [id]="question.key" [type]="question.type">
<input *ngIf="question.type=='checkbox'" [formControlName]="question.key"
        [id]="question.key" type="checkbox">
</ng-container>

您可以成为stackblitz

中的示例

Other Idea是创建一个新类型,“复选框”和一个新的switchCase选项。 新的CheckBoxQuestion是文本框的副本

export class CheckBoxQuestion extends QuestionBase<boolean> {
  controlType = 'checkbox';

  constructor(options: {} = {}) {
    super(options);
  }
}

然后添加switchCase

<input *ngSwitchCase="'checkbox'" type="checkbox" [formControlName]="question.key">

,在堆叠闪电战中,您有两种情况

注意:您正在创建一个大型循环

<div [formGroup]="form">
   <input formGroupName="question.key">
</div>
<div [formGroup]="form">
   <input formGroupName="question.key">
</div>
   ...

我建议将您的dynamic-form-question.component.html更改为简单创建

<div>
  <input [formControl]="form.get(question.key)" ..>
</div>

是的,将组合[formGroup] =“ form” .. formControlName =“ ..”更改为[formControl] =“ form.get(..”))。