DEV Community

CraigSmith789
CraigSmith789

Posted on

Add an input field in Angular

Lets walk through adding a simple input form to an Angular application.
To get started we need to import Reactive Forms module into our NG module. We can open our app.module.ts file and add the following.
Alt Text

While we are in this file we can also update our imports array.
Alt Text

Now lets jump over to the component that we would like to add the form to. We will first need to import FormBuilder from angular/forms.
Alt Text
Then build a model on our component.
We need to add a property to our class that will represent that model in the Reactive form. Let’s name it todo form.
Alt Text

Now jump down to the constructor and we can add something that Reactive Forms provides us called form building. We can add private FormBuilder, and that's going to be of the type FormBuilder. We will also need to define a group of controls for our form.

Next we add this.todoForm equal to this.formBuilder.group. Next we add an object, title and set it to an empty string.

Alt Text
Now that we have our model set up, we can start to work on template in our template HTML. We are going to create a basic form with a text input to add a new todo and a submit button.

Just a few remaining steps. Our reactive form needs to be bound to a form group. We can also pass in our existing todoForm.
We also need to bind our text field to the title field.
Next we need to bind to the submit event of the form using an Angular event called ngSubmit and pass in a function.
Alt Text
Define our function and push our new todo to the array.
Alt Text

And that's it. You've just created a reactive form in Angular.

Top comments (0)