基于Angular2 Dynamic Forms Cookbook,我使用高级模型制作了一个应用程序。现在我面临的问题是我无法获得复选框组的值。 https://github.com/philipphalder/angular2-dynamic-forms-advanced
回复Github:https://github.com/philipphalder/angular2-dynamic-forms-advanced
答案 0 :(得分:0)
感谢您实施解决方案。 我更新了我的回购。 https://github.com/philipphalder/angular2-dynamic-forms-advanced
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);
}
<!-- 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>
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);
}
}