AngularJS Form: Template-driven

Forms are widely used in any kind of applications. You can find a form in an ordering food app, a buying things app, a social media app, a blog with a contact form, etc. Forms are there where an app needs some data from the user.

This article describes how to create a template-driven form with client-side validation in AngularJS 7. Additionally, you will find out how to create cascading dropdown and how to make your form prettier with Bootstrap 4.

The code of a form is on my Github.

template-driven angularjs form
The Output Form

Environment Set Up

Implementation of AngularJS apps is much easier with Node.js, npm, Angular CLI.

First of all, install Node.js. In a nutshell, Node.js is a JavaScript runtime environment. With Node.js you receive npm, which is Node.js package manager. It allows installing JavaScript libraries via command line. After the installation of Node.js type the following command to install Angular CLI.

Angular CLI is an abbreviation for Angular command line interface. It is a tool for building, deploying, testing, etc. by running commands via command line. However, if you do not like commands, you can use an app which has features of CLI.

Create an App

Use Angular CLI to create an app. Type following command, changing ‘app-name’.

CLI will ask you several questions regarding the app’s settings. Leave default settings by clicking ‘enter’ on each question. It will create a folder ‘app-name’.

Being inside ‘app-name’ folder, type below command to compile the app and to open it in a browser.

Each saved change of the project will trigger compiling and reloading the page.

Default Angular app contains one module called AppModule and one component – AppComponent. Angular app is built of modules and components. Modules are bags of features. Among the features, there are components.

Module must have a decorator @NgModule. The decorator has the following properties:

  • declarations property contains a collection of the module’s components,
  • imports property has modules which are used by the module’s components,
  • bootstrap property owns only one component – a root component. Root component is responsible for holding other components of the module.

Create a Form

Angular has two different approaches for creating forms – template-driven and reactive. The template-driven form has more control of a form logic by a template than by a component class. Therefore it is recommended for simple forms, where tests are not necessary and a model is not complex.

A form will be a component of AppModule. Let’s create it via CLI.

The component may be implemented without CLI. You may create a sample-form folder in the app folder and two essential files: sample-form.component.html and sample-form.component.ts. Names of files do not matter for Angular compiler but it is a good practice to name them as ‘component-name.component’. Moreover, you must add SampleFormComponent to declarations in AppModule.

A component must have a @Component decorator. As you can see, the component class has a template in ‘./sample-form.component.html’ file and the template can be used by putting ‘app-sample-form’ HTML tag into another template.

Submit Filled Form

Before you will kick off implementing a form, add FormsModule to imports in AppModule.

That’s what we need to submit a form:

Firstly, we need to gather filled data. Each HTML tag, which is used to input data, needs ‘name’ and ngModel directive. Angular directive is a part of HTML tag, adds logic to the tag. In this case the directive creates a property called ‘firstName’ which contains text received from the input tag. Which object contains the property?

ngForm creates the object containing each property within the form. #formResult instantiates a local template variable called ‘formResult’ and assigns the object created by ngForm to the variable. ngSubmit with brackets binds onFormSubmitted handler to a submit event. What does it mean in practice? It means that when a user clicks on a submit button, the method onFormSubmitted will be executed. The round brackets determine one-way data binding where data goes from a template to a class component.

Cascading Dropdown

Cascading dropdown is populated depending on another dropdown. In the app, there are two dropdowns – for selecting a country and city. Dropdown of cities is a cascading dropdown.

The component class contains countries property. The template reads the countries and creates each ‘option’ by looping option tag with country data. *ngFor directive does the looping. Selected country value goes to the onCountrySelected function. Country id is a value of ‘option’ because of property binding. Property binding binds a variable to an HTML attribute and changes the value if the passed variable has changed. The ‘option’ displays a country name with the use of interpolation. Both interpolation and property binding are one-way bindings where data goes from a component class to a template.

onCountrySelected function filters collection of countries by country id and assigns the result to selectedCities property.

Angular will render the above code if selectedCities is different than null and the collection contains some item. *ngIf is a structural directive as *ngFor. Structural directives make changes in DOM. They determine whether a tag is removed or added.

Client-Side Validation

Client-side validation is a check on a frontend whether input meets certain conditions.

If user doesn’t fill in last name, a form will display a warning. Local template variable lastName will contain ‘errors’ property in case of invalid input. If errors are related to ‘required’ restriction then the errors property will contain ‘required’ property. Angular has another validation restrictions – check it in a code on my Github.

Local template variable formResult is useful either for disabling the submit button.

Make the Form Prettier

Install Bootstrap 4.

Go to angular.json file and paste a bootstrap path to “styles”.

  • ‘container’ – a required class to create a Bootstrap grid system,
  • ‘mt-4’ – a new class since Bootstrap 4, creates a margin,
  • ‘row’ – a part of the grid system, creates a row
  • ‘col-sm-6’ – a part of the grid system as well, two tags with the class create two columns,
  • mx-auto’ – horizontally moves an element to the center,
  • btn btn-success’ – a green button class.

Conclusion

To sum up, let’s have a look at a nutshell instruction of how to create a template-driven form with client-side validation and cascading dropdown:

  • create a component for the form – an HTML template and component class,
  • use ngForm and ngModel directives to gather form’s data,
  • implement one-way binding for ngSubmit to pass the form’s data to the component class,
  • use structural directive *ngIf to hide empty cascading dropdown and *ngFor to populate dropdowns,
  • implement property binding to assign an option tag value by for instance [value]=”city.id” and one-way binding to pass selected ‘parent’ dropdown value to the class component – (change)=”onCountrySelected($event.target.value)” ,
  • create a local template variable to check if user input is valid, for example #lastName=”ngModel” ,
  • deactivate submit button dynamically, if a form is invalid by property binding and local template variable[disabled]=”formResult.invalid” .

Don’t forget to make your form prettier with the use of some UI library or simply CSS. A user would not like to use an ugly form! 🙂

0 0 vote
Article Rating
Share on
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments