基于Angular2动态形式cookbook的一组复选框

时间:2017-06-01 07:19:11

标签: javascript angular angular2-forms

基于Angular2 Dynamic Forms Cookbook,我使用高级模型制作了一个应用程序。现在我面临的问题是我无法获得复选框组的值。 https://github.com/philipphalder/angular2-dynamic-forms-advanced

这是问题所在。 Here is the problem

回复Github:https://github.com/philipphalder/angular2-dynamic-forms-advanced

1 个答案:

答案 0 :(得分:0)

感谢您实施解决方案。 我更新了我的回购。 https://github.com/philipphalder/angular2-dynamic-forms-advanced

动态form.component.ts

import { CheckboxQuestion } from '../../models/question-checkbox';

onSubmit() {
 let result = Object.assign({}, this.form.value);
 const checkboxQuestions = this.questions.filter(x => x instanceof CheckboxQuestion) as CheckboxQuestion[];
 Object.keys(this.form.value)
   .filter(x => x === 'checkbox')
   .forEach(x => {
     result[x] = checkboxQuestions[0].options
       .filter((y, n) => result[x][n])
       .map(z => z.value);
 });
 this.payLoad = JSON.stringify(result);
}

动态question.component.html

<!-- CHECKBOX -->
<div *ngSwitchCase="'checkbox'" class="question-card-container" >  
  <md-card class="question-card" [formArrayName]="question.key"> 
        <label [attr.for]="question.key">{{question.label}}</label> 
        <md-checkbox class="phil-checkbox" *ngFor="let opt of question.options; let i = index" [formControlName]="i">{{opt.value}}</md-checkbox>
    <div class="errorMessage" *ngIf="!isValid">{{question.label}} is required</div>
  </md-card>
</div>

问题-control.service.ts

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

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

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

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

questions.forEach(question => {
  if (question.key === 'checkbox') {
    group[question.key] = new FormArray((question as any).options
      .map(x =>  {
        return new FormControl(question.value && question.value.some(y => y === x.value) ? x.value : '');
      }));
    return;
  }
  group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
    : new FormControl(question.value || '');

});
return new FormGroup(group);
}
}