1
votes

I am trying to build a dynamic form. In my particular case, I need a form where user can define a question and add its options dynamically.

The question title is a text field where user enter the question. The option field is also a text field where user add options for the question. A user can add 2 or more options for a particular question.

I am using Formbuilder and have something like this:

this.form = fb.group({
            title: ["", Validators.required],
            options:
            fb.group({
                option1: new Control(''),
                option2: new Control('')
                .....
            })
        });

I also know we can add control to a form group using this.form.addControl, and remove control using this.form.removeControl.

I need to allow user to add/remove options, but I am note sure how to name these dynamically added options so that when I submit response, I have the below posted to the server:

{
title:"My test question",
options:{
"option 1","option 2","option 3",.......
}
}

Can anyone please guide? Any help would be highly appreciate.

1
Here you have more info about Dynamic Forms in Angular 2: playcode.org/dynamic-forms-in-angular-2 - Eusthace
Thank you Mayur and Eusthace, both of the links generate a form one time only from a model. What I need is allow user to add or remove a control to the form group once it has been generated. For example user can define a question with n number of options. When user clicks add question, it display a textbox for question text and two default text boxes to enter options text, I want to allow user to add additional options as well, e.g. clicking add more option should show another textbox to add option, similarly he should be able to delete an added option which should remove option textbox. - Naveed Ahmed

1 Answers

1
votes

Take a look at the official documentation. There is an article specific to this topic: https://angular.io/guide/dynamic-form