Form Element Values As Json Using Angular Form
I am making angular 6 application where i am using Angular dynamic form Here i have made a nested input fields in which there will be two input textboxes at the initial stage and
Solution 1:
@Many, when you have type array, you must create the children before push the array.
...
} elseif (element.elementType === 'array') {
letchildren:any[]=[]; //declare children//each children of element fill our array children
element.children.forEach(e=>{
if (e.elementType === 'textbox') {
children.push(newTextboxQuestion(e));
}
})
//Hacemos un push not of element else element + the property children//changed (it will be the array created)
questions.push(newArrayQuestion({...element,children:children}));
}
Solution 2:
You must add a new type "check-box"
exportclassCheckBoxQuestionextendsQuestionBase<string> {
controlType = 'checkbox';
type: boolean;
constructor(options: {} = {}) {
super(options);
}
}
And change the dinamic Form question
<div [formGroup]="form"><!--the label only show if it's NOT a checkbox ---><label *ngIf="question.controlType!='checkbox'" [attr.for]="question.key">{{question.label}}</label><div [ngSwitch]="question.controlType">
...
<!--add type checkbox--><ng-container *ngSwitchCase="'checkbox'"><input [formControlName]="question.key"type="checkbox"
[id]="question.key" ><label [attr.for]="question.key">{{question.label}}</label></ng-container>
...
</div>
And question service to take account the new checkbox
elseif (e.elementType === 'checkbox') {
children.push(new CheckBoxQuestion(e));
}
Update if we want to add more validators, take a look at the function "toFormGroup" of question.service.ts
toFormGroup(questions: QuestionBase<any>[]) {
letgroup: any = {};
questions.forEach(question => {
if (question.controlType=="array") {
group[question.key]=newFormArray([]);
}
else {
//create an array of "validators"letvalidators:any[]=[];
//If question.required==true, push Validators.requiredif (question.required && question.controlType!='checkbox')
validators.push(Validators.required);
//...add here other conditions to push more validators...
group[question.key] = newFormControl(question.value || '',validators);
}
});
returnnewFormGroup(group);
}
Update two it's necesary change too the questionbase.ts to add this properties
exportclassQuestionBase<T> {
value: T;
...
maxlength:number;
minlength:number;
constructor(options: {
value?: T,
....
minlength?:number,
maxlength?:number,
controlType?: string,
children?:any
} = {}) {
this.value = options.value;
....
this.minlength = options.minlength;
this.maxlength = options.maxlength;
...
}
}
For see the errors you must as about form.get(question.key).errors, e.g
<div class="errorMessage"
*ngIf="form.get(question.key).errors?.required">
{{question.label}} is required
</div>
Tip: for know about your errors use
{{form.get(question.key).errors|json}}
See the forked stackblitz
Post a Comment for "Form Element Values As Json Using Angular Form"