Tech: Building Dynamic Form in Angular 9 and Ivy — Part 2

Make Reactive Form Great Again!!!

Image for post
Image for post

Consuming Dynamic Form

// form-config.tsexport const FormConfig: DynamicFieldModel[] = [
{
label: "Text",
name: "text",
type: "text"
},
{
label: "Select",
name: "select",
type: "select",
options: [
{ label: "Option 1", value: "1" },
{ label: "Option 2", value: "2" },
{ label: "Option 3", value: "3" }
]
},
{
label: "Datepicker",
name: "datepicker",
type: "datepicker"
}
];
// dynamic-form.component.ts@Component({
selector: "app-dynamic-form",
template: `
<form [formGroup]="formGroup">
<div *ngFor="let field of formConfig">
<app-dynamic-field
[formGroup]="formGroup"
[name]="field.name"
[type]="field.type"
[label]="field.label"
[options]="field.options || []">
</app-dynamic-field>

</div>
</form>
`
})
export class DynamicFormComponent implements OnInit { formGroup: FormGroup; formConfig = FormConfig; constructor(private fb: FormBuilder) {} ngOnInit() {
this.buildForm(this.formConfig);
}
buildForm(formConfig: DynamicFieldModel[]) {
let form = {};
formConfig.forEach(field =>
(form = { ...form, [field.name]: new FormControl("") })
);
this.formGroup = this.fb.group(form);
}}
Image for post
Image for post

Wrap Up

Did you see my other posts?

Written by

Front End architect, opensource contributor and investment enthusiast. New content posted every week.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store