Form generator in Angular 8 to validate response forms

Form generator in Angular 8 to validate response forms

Previously, we discussed how to manage reactive form controls with form groups in Angular 8. This is a new post on building reactive forms in Angular 8. Here’s a brief recap of the concepts we discussed in the last post.

Forms controls and form groups in Angular

Form controls are basically classes that can hold both the data values and the validation information of any form element, which means to say every form input you have in a reactive form should be bound by a form control. They are the basic units that make up reactive forms.

Form groups are constructs that basically wrap a collection of form controls. Just as the control gives you access to the state of an element, the group gives the same access, but to the state of the wrapped controls. Every single form control in the form group is identified by name when initializing.

Generating form controls

Setting up form controls, especially for very long forms, can quickly become both monotonous and stressful. Angular provides a helper service to solve this problem so that you can always obey the DRY concept of avoiding repetition. This service is called the form builder service.

Before we start…

To be able to follow through this article’s demonstration, you should have:

  • Node version 11.0 installed on your machine
  • Node Package Manager version 6.7 (usually ships with the Node installation)
  • Angular CLI version 8.0
  • The latest version of Angular (version 8)
// run the command in a terminal
ng version

  • Node version 11.0 installed on your machine
  • Node Package Manager version 6.7 (usually ships with the Node installation)
  • Angular CLI version 8.0
  • The latest version of Angular (version 8)
npm install

Other things that would be nice to have are:

  • Node version 11.0 installed on your machine
  • Node Package Manager version 6.7 (usually ships with the Node installation)
  • Angular CLI version 8.0
  • The latest version of Angular (version 8)
Demo

In this tutorial, you will be taken through a code-along journey building a reactive form with the form builder. If you have followed this post from the start, you will have downloaded and opened the starter project in VS Code. If you open the employee.component.ts, file it should look like this:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms'
@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
  bioSection = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    age: new FormControl(''),
    stackDetails: new FormGroup({
      stack: new FormControl(''),
      experience: new FormControl('')
    }),
    address: new FormGroup({
        country: new FormControl(''),
        city: new FormControl('')
    })
  });
constructor() { }
ngOnInit() {
  }
  callingFunction() {
    console.log(this.bioSection.value);
   }
}

You can see that every single form control — and even the form group that partitions it — is spelled out, so over time, you as the developer keep repeating yourself. The form builder helps to solve this efficiency problem. To use the form builder, you must first register it.

Registering the form builder

To register the form builder in a component, the first thing to do is import it from Angular forms:

import { FormBuilder } from ‘@angular/forms’;

The next step is to inject the form builder service, which is an injectable provider that comes with the reactive forms module. You can then use the form builder after injecting it. Navigate to the employee.component.ts file and copy in the code block below:

import { Component, OnInit } from '@angular/core';
import { FormBuilder } from '@angular/forms'
@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {
  bioSection = this.fb.group({
    firstName: [''],
    lastName: [''],
    age: [''],
    stackDetails: this.fb.group({
      stack: [''],
      experience: ['']
    }),
    address: this.fb.group({
        country: [''],
        city: ['']
    })
  });
constructor(private fb: FormBuilder) { }
ngOnInit() {
  }
  callingFunction() {
    console.log(this.bioSection.value);
   }
}

This does exactly the same thing as the previous code block you saw at the start, but you can see there is a lot less code and more structure — and, thus, optimal usage of resources. Form builders not only help to make your reactive forms’ code efficient, but they are also important for form validation.

Form validation

Using reactive forms in Angular, you can validate your forms inside the form builders. Run your application in development with the command:

ng serve

You will discover that the form submits even when you do not input values into the text boxes. This can easily be checked with form validators in reactive forms. The first thing to do, as with all elements of reactive forms, is to import it from Angular forms.

import { Validators } from '@angular/forms';

You can now play around with the validators by specifying the form controls that must be filled in order for the submit button to be active. Copy the code block below into the employee.component.ts file:

The last thing to do is to make sure the submit button’s active settings are set accordingly. Navigate to the employee.component.html file and make sure the submit statement looks like this:

<button type=”submit” [disabled]=”!bioSection.valid”>Submit Application</button>

If you run your application now, you will see that if you do not set an input for first name, you cannot submit the form — isn’t that cool? There are many more cool form validation tips you can get from the official guide here.

Displaying input values and status

The last thing you should know is how to use the value and status properties to display, in real time, the input values of your reactive form and whether it can be submitted or not.

The reactive forms API lets you use the value and status properties on your form group or form controls in the template section. Open your employee.component.html file and copy in the code block below:

<form [formGroup]="bioSection" (ngSubmit)="callingFunction()">
    <h3>Bio Details
</h3>

  <label>
    First Name:
    <input type="text" formControlName="firstName">
  </label> <br>
<label>
    Last Name:
    <input type="text" formControlName="lastName">
  </label> <br>
<label>
    Age:
    <input type="text" formControlName="age">
  </label>
<div formGroupName="stackDetails">
    <h3>Stack Details</h3>

    <label>
      Stack:
      <input type="text" formControlName="stack">
    </label> <br>

    <label>
      Experience:
      <input type="text" formControlName="experience">
    </label>
  </div>
<div formGroupName="address">
    <h3>Address</h3>

    <label>
      Country:
      <input type="text" formControlName="country">
    </label> <br>

    <label>
      City:
      <input type="text" formControlName="city">
    </label>
  </div>
<button type="submit" [disabled]="!bioSection.valid">Submit Application</button>
  <p>
    Real-time data: {{ bioSection.value | json }}
  </p>
  <p>
    Your form status is : {{ bioSection.status }}
  </p>
</form>

This displays both the value and the status for submission for you in the interface as you use the form. The complete code to this tutorial can be found here on GitHub.

Conclusion

This article gives an overview of the form builder and how it is a great efficiency enabler for form controls and form groups. It also shows how important it can be for handling form validation easily with reactive forms. Happy hacking!

Originally published by*** *Nwose Lotanna **at blog.logrocket.com

==========================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Angular 8 (formerly Angular 2) - The Complete Guide

Angular 8 - Reactive Forms Validation Example

Angular 8 User Registration and Login Example and Tutorial

Angular 8 Features: Angular 8 Released with New Features

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

What’s new in HTML6

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

Hire Now: https://bit.ly/394wdOx

Important reasons for developers to adopt Angular JS development

 Important reasons for developers to adopt Angular JS development

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular...

In the current scenarios, e-commerce companies are very keen to create an online impact. The web and app development market are at its peak of popularity. There is a high demand for web and app developers with a growing number of websites. Angular has been a top choice for web development and it's the latest version AngularJS has gained popularity in the industry. This java script framework has created its prominent position in creating web apps.
Regardless of whether there are numerous different systems accessible for web development, AngularJS can support among them all. Since its introduction in the market, Angular has been creating waves in the market.

Introduction

Angular js is a powerful framework that was developed by Google. It is used to build dynamic apps with power-packed features. It was first introduced in 2010 and created by developers at Google. This framework was created to simplify and remove the challenges in creating dynamic apps. It uses HTML, CSS, and java script to create dynamic single-page applications. Angular Js is inclusive of Mongo DB and it is a frontend fragment of Mean Stack. In the developer's community, Angular is considered as a reliable and fast Java script framework. Many popular apps like PayPal. You tube, Netflix, the guardian, Lego are built using the AngularJS framework.

In this blog, we are listing some compelling reasons to pick angular development to familiarize you with its potential

• Open-source framework: It is not a library but open-source frameworks that enable the developers to build well-performing single page web applications. Just after its launch, it became hugely popular among the developers and it is not going to come at a halt.

• Simplified MVC structure: Developers use AngularJS to build robust and interactive web applications. AngularJS framework uses MVC architecture to create interactive applications. AngularJS makes it easy for developers to create apps as they are only required to split the applications.

• Extensive community: As angular is built by Google, it is backed by a very large community of professionals. The Angular JS conferences of the professionals are held all over the world. Hackathons are also organized in IT communities that include some professional and skilled engineers who can help with the queries and questions related to Angular.

• Declarative code system: In Angular JS developers can create declarative patterns by using declarative paradigms. It enables developers to be less heavy, and easy to read. In this framework, the developers get data models that are not too complex to write that abolishes the need to use any getter/setters and with easy data manipulation.

• Two-way data binding: It is one of the impeccable features that makes Angularjs popular in the developers' community. It allows seamless projections of the models and data binding. In this framework, any changes in the user interface make an impact on the application objects. The developers are not required to fresh the cycle and that makes it vulnerable to bugs.

• Using directives: AngularJS makes use of Directives as the developers can build custom HTML tags that function as custom widgets and it can be possible using directives. Its implications are also in the case of the use of decorating components and manipulation of DOM elements in appealing ways.

• Enterprise-level testing: When using Angular JS there is no need for demanding any other supplementary framework or additional plugins. In the process, parts of applications are put in the angular framework which is not too complex for manipulation. In module separation, developers can load essential services in an effective way for the performance of automatic testing.

• Client-side situation: AngularJS mainly works at the client-side and it is fully compatible with both web and mobile browsers. It can function with any projects without the need for any backend notifications. The developers can easily use AngularJS for the front end of applications.

• Easy to use: AngularJS is rich with its features and facilitates developers to reduce any need for writing codes. It reduces the burden of developers by the application of MVC architecture and data models.

Many other significant features make AngularJS prioritize by the developers than other Javascript frameworks. The above-mentioned reasons have made it the top choice for reputed companies all across the globe for web development. Developers at the company master the skills to work with Angular JS development for web. The company is equipped with dedicated professionals having sound technical knowledge of working with AngularJS. We offer offshore services to extend our reach all across the globe with various models. We have more than 15 years of experience in the industry that we use to deliver high-quality solutions by leveraging the latest technology and quality standards.

Mobile App Development Company India | Ecommerce Web Development Company India

Mobile App Development Company India | Ecommerce Web Development Company India

Best Mobile App Development Company India, WebClues Global is one of the leading web and mobile app development company. Our team offers complete IT solutions including Cross-Platform App Development, CMS & E-Commerce, and UI/UX Design.

We are custom eCommerce Development Company working with all types of industry verticals and providing them end-to-end solutions for their eCommerce store development.

Know more about Top E-Commerce Web Development Company