UNPKG

cd-force

Version:

Form creation goodness.

87 lines (71 loc) 2.56 kB
import { CheckboxControl } from '../models/control-checkbox'; import { ControlBase } from './../models/control-base'; import { FormCreatorService } from './../form-creator.service'; import { Component, Input, OnInit } from '@angular/core'; import { FormGroup, FormArray, FormBuilder } from '@angular/forms'; import { CheckboxOption, CheckboxConfig } from '../models/checkbox.model'; @Component({ selector: 'dynamic-form', templateUrl: './dynamic-form.component.html', providers: [FormCreatorService] }) export class DynamicFormComponent implements OnInit { // List of controls to display and capture input from the user from. @Input() controls: ControlBase<any>[]; @Input() checkboxes; // One group to capture non-checkbox controls in the form. form: FormGroup; // Groups to capture checkboxes. group1: FormGroup; group2: FormGroup; group3: FormGroup; // Object to store captured input from user into. values: any; constructor(private fcs: FormCreatorService, private fb: FormBuilder) { } ngOnInit() { this.form = this.fcs.toFormGroup(this.controls); this.group1 = this.fb.group({ items: this.fcs.toFormGroupItems(this.checkboxes[0]['options'] as Array<CheckboxOption>) }); this.group2 = this.fb.group({ items: this.fcs.toFormGroupItems(this.checkboxes[1]['options'] as Array<CheckboxOption>) }); this.group3 = this.fb.group({ items: this.fcs.toFormGroupItems(this.checkboxes[2]['options'] as Array<CheckboxOption>) }); } get group1items() { return this.group1.get('items'); } get group2items() { return this.group2.get('items'); } get group3items() { return this.group3.get('items'); } onSubmit() { this.values = this.form.value; if (this.checkboxes[0] !== undefined) { this.values[this.checkboxes[0].key] = this.mapCheckboxAnswers(0, this.group1.value); if (this.checkboxes[1] !== undefined) { this.values[this.checkboxes[1].key] = this.mapCheckboxAnswers(1, this.group2.value); if (this.checkboxes[2] !== undefined) { this.values[this.checkboxes[2].key] = this.mapCheckboxAnswers(2, this.group3.value); } } } } mapCheckboxAnswers(groupId, groupValue) { const answers = Object.assign({}, groupValue, { value: groupValue.items.map((s, i) => { return { id: this.checkboxes[groupId]['options'][i].id, selected: s, label: this.checkboxes[groupId]['options'][i].label }; }) }); return answers.value; } }