Reader small image

You're reading from  Spring Boot and Angular

Product typeBook
Published inDec 2022
Reading LevelBeginner
PublisherPackt
ISBN-139781803243214
Edition1st Edition
Languages
Right arrow
Authors (2):
Devlin Basilan Duldulao
Devlin Basilan Duldulao
author image
Devlin Basilan Duldulao

Devlin Basilan Duldulao is a full-stack engineer with over 8 years of web, mobile, and cloud development experience. He has been a recipient of Microsoft's Most Valuable Professional (MVP) award since 2018 and earned the title of Auth0 Ambassador for his passion for sharing best practices in application security. Devlin has passed some prestigious software and cloud development exams, such as MSCD, Azure Associate Developer, AWS Associate Developer, and Terraform Associate. He has also authored the book ASP.NET Core and Vue.js and coauthored the book Practical Enterprise React in 2020 and 2021, amid the pandemic.
Read more about Devlin Basilan Duldulao

Seiji Ralph Villafranca
Seiji Ralph Villafranca
author image
Seiji Ralph Villafranca

Seiji Ralph Villafranca graduated Cum Laude with a degree of Bachelor of Science In Computer Science at University of Santo Tomas in the Philippines. He has 6 years of experience in Web and Mobile Development and has also earned the title of Auth0 Ambassador for having passions in application securities, He holds several certifications in Angular Development from Beginner to Expert Level. Seiji is also one of the Community Leaders of Angular Philippines which is the largest Angular group in the Philippines, the community has lead him to speak in different meetups of tech communities, workshops and even local and international conferences, he is enthusiastic in sharing knowledge in coding, organizing events and meetups for the community as well as writing content for students and professionals. He also has been a mentor in several hackathons as he loves the startup community. Seiji loves to develop new projects that are on web or mobile, he is currently a senior software engineer in a company based in Malaysia, He is not just a coder but also a mentor, teacher and trainer for students, professionals and companies.
Read more about Seiji Ralph Villafranca

View More author details
Right arrow

Building Reactive Forms

In the previous chapter, we have already learned how to structure our Angular application at the module and component level, which promotes the maintainability of code, especially in enterprise applications. We have organized modules into three categories: core modules, shared modules, and feature modules. We have also grouped components into two classifications: Smart and Dumb components, which separate components that retrieve data and have dependencies from components that are for presentation purposes only.

We have also discussed how to configure and implement Angular Material, which is a UI library that provides ready-to-use components and base styling for our Angular application.

In this chapter, we will now start learning how to build forms using reactive forms in Angular. We will understand form groups, form controls, and form arrays and create validations in our form.

In this chapter, we will cover the following topics:

  • Understanding...

Technical requirements

Here is a link to the finished version of this chapter:

https://github.com/PacktPublishing/Spring-Boot-and-Angular/tree/main/Chapter-11

Understanding reactive forms

One of the advantages of the Angular framework is that it already provides its form extensions. We can find these extensions under the @angular/forms package once we have created our Angular application. There are two available ways to build forms. These are template-driven forms and reactive forms; them having their own form extension is advantageous to the developers as this does not require installing under packages to create forms.

At the same time, we can make sure that every Angular application uses a single library for building forms. In this section, we will be focusing more on how to implement reactive forms in our application as this is the commonly used method in developing forms in Angular applications, but first, let’s discuss a basic introduction to the template-driven approach before proceeding to reactive forms.

The template-driven approach

Template-driven forms, as the name suggests, are forms declared and validated on the...

Basic form controls

This section will now discuss more of the concepts of form controls in reactive forms. We have already created an example of form controls in the previous section, but now, we will discover more about the functions and capabilities of form controls in Angular.

Form controls represent a single form element inside a form; they store the value of a form element that allows us to retrieve data of each input. This can be input, textarea, or any element that accepts values. When used in Angular, form controls can be instantiated by adding new FormControl('') code; we can see that it takes a single argument that defines the values of the control. These values can be null as form controls can be reset.

Form controls are like the properties of a JSON object, but compared to JSON, each control has its methods that will help us control, modify, and validate the values.

Next, let’s have a look at the different methods and features of form controls...

Grouping form controls

This section will now discuss how to group form controls in our application. Forms contain several related controls, which is why it is necessary to group them for a better structure. Reactive forms provide two ways to group form controls, as follows:

  • Form group: Creates a form with a fixed set of form controls. Form groups can also contain another set of form groups to handle complex forms.
  • Form array: Creates a form with dynamic form controls. It can add and remove form controls and at the same time can contain other form arrays to handle complex forms.

Creating form groups

Form groups allow us to control the values and status of form controls by groups. We can also access a single form control inside a form group using its name. To create a form group, let’s follow the next steps:

  1. Let’s say we have a HeroComponent; for example, the first step is to import the FormGroup and FormControl classes from the @angular/forms...

Using the FormBuilder service to generate controls

In the previous section, we successfully created reactive forms using form groups, form arrays, and form controls. However, as we can see from the syntax, creating forms becomes repetitive. We are always instantiating new instances of form controls, form arrays, and form groups, and this is not ideal in larger forms. FormBuilder provides the solution for this issue.

This is a service that can be injected into our components to generate groups, controls, and arrays without instantiating new ones. To create a reactive form using FormBuilder, we will be following the next steps:

  1. We will be transforming the form in the previous section using FormBuilder. The first step is to import the FormBuilder service into our component from @angular/forms:
    import { FormBuilder } from '@angular/forms';
  2. The next step is to inject the FormBuilder service into our component:
    export class HeroComponent implements OnInit {
     powerFormArray...

Validating form input

We have now created and simplified our reactive form in the previous section, but we want to make our forms accurate in accepting data and at the same time create a user-friendly experience for the user to let them know easily what the valid values for each control are. Now, we will learn how to add validations to our reactive forms.

In reactive forms, we are adding validators as parameters directly to the form controls in the component class instead of adding them as an attribute in the template.

Built-in validators

Angular provides several built-in validator functions that we can use directly in our forms. Let’s have a look at some of these:

  • static min(min: number)—Requires the value of the control to be equal to or greater than the given number:
    form = this.fb.group({
      name: [10, [Validators.min(4)]]
    });
    console.log(this.form.status) // returns VALID
    static max(max: number) – requires the value of the control to be...

Summary

With this, we have reached the end of this chapter; let’s have a recap of the valuable things you have learned. You have learned about the concepts and implementation of Angular reactive forms, and we have implemented FormGroup, FormBuilder, and formControlName directives to bind input values to capture data in our form. We have also discussed how to group form controls for binding nested properties and create form arrays in our reactive forms. This is primarily useful if some objects we want to display have array values.

At the same time, we want to accept a list of entries from users. Lastly, we have also learned how to implement validations for form controls to handle and verify user input, which will be beneficial for the user experience and help avoid unexpected errors.

In the next chapter, we will learn about the concepts and implementation of state management in Angular applications; we will discuss the idea of the Redux pattern and the NgRx library in terms...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Spring Boot and Angular
Published in: Dec 2022Publisher: PacktISBN-13: 9781803243214
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Devlin Basilan Duldulao

Devlin Basilan Duldulao is a full-stack engineer with over 8 years of web, mobile, and cloud development experience. He has been a recipient of Microsoft's Most Valuable Professional (MVP) award since 2018 and earned the title of Auth0 Ambassador for his passion for sharing best practices in application security. Devlin has passed some prestigious software and cloud development exams, such as MSCD, Azure Associate Developer, AWS Associate Developer, and Terraform Associate. He has also authored the book ASP.NET Core and Vue.js and coauthored the book Practical Enterprise React in 2020 and 2021, amid the pandemic.
Read more about Devlin Basilan Duldulao

author image
Seiji Ralph Villafranca

Seiji Ralph Villafranca graduated Cum Laude with a degree of Bachelor of Science In Computer Science at University of Santo Tomas in the Philippines. He has 6 years of experience in Web and Mobile Development and has also earned the title of Auth0 Ambassador for having passions in application securities, He holds several certifications in Angular Development from Beginner to Expert Level. Seiji is also one of the Community Leaders of Angular Philippines which is the largest Angular group in the Philippines, the community has lead him to speak in different meetups of tech communities, workshops and even local and international conferences, he is enthusiastic in sharing knowledge in coding, organizing events and meetups for the community as well as writing content for students and professionals. He also has been a mentor in several hackathons as he loves the startup community. Seiji loves to develop new projects that are on web or mobile, he is currently a senior software engineer in a company based in Malaysia, He is not just a coder but also a mentor, teacher and trainer for students, professionals and companies.
Read more about Seiji Ralph Villafranca