Angular NgForm

In this section, we will add a form using Angular’s built-in directive ngForm. For this exercise, a new project is made.

First thing we need to do is properly integrate Bootstrap 4 and import the modules especially the Forms module in the app.component.ts.

ngform

Next, we will create a class named stock. Let’s do it via Angular-CLI. Open your integrated terminal and enter the command ng g class Stock.

ngform

  • These are made as the objects for our forms

In the app.component.ts, import our new Stock class and create the variables submitted and newStock that follows the format shown below.

ngform

Just below the same AppComponent class, create two new methods: onSubmit() and cancel().

ngform

Next, go to app.component.html and clear the default code. Here is where we are going to make our forms.

ngform

  • This container uses the ngForm directive
  • A basic two input fields are made. One for stock name and one for stock code.
  • The button ‘Submit’ simply calls the onSubmit() method we created earlier. It does not have any function for now.
  • Don’t forget to include ‘required’ in your input fields.

Save your work and open your integrated terminal. Enter the command ng serve and open your browser to localhost:4200

6a

Success! Our form is now operational.

Lastly, we are going to create a ngIf that disables this form when the button ‘Submit’ is clicked. As you remember, the variable ‘submitted’ is set to false by default. When using onSubmit() method, the variable will be changed to true.

7a

Once the SUBMIT button is clicked, then the onSubmit() method will be called and afterwards, the submitted variable will be set to true. The ngIf  directive checks the value of the submitted variable and since the value is true, this Stock Form is shown.

8a

  • A simple style is added to the <h2> tag

Another <div> is added to show the word “Submitted!” when the button Submit is clicked.

9a

10a

All done! That is how a form can be added using ngForm.

On the next article in the FORMS series, you will learn Form Validation.

Subscribe Now and Upgrade Your Skills Today!
Sign up now and have the latest tech tutorials delivered straight to your mailbox.

PLUS: Get exclusive member-only discounts (up to 80% OFF!!) on our top tech courses in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.