First thing we need to do is properly integrate Bootstrap 4 and import the modules especially the Forms module in the app.component.ts.
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.
- 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.
Just below the same AppComponent class, create two new methods: onSubmit() and cancel().
Next, go to app.component.html and clear the default code. Here is where we are going to make our forms.
- 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
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.
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.
- A simple style is added to the <h2> tag
Another <div> is added to show the word “Submitted!” when the button Submit is clicked.
All done! That is how a form can be added using ngForm.