×

AngularJS Tutorial

AngularJs Questions

AngularJS Practice

Angular - Reactive Forms

In this tutorial, we will learn about reactive forms (how to use reactive forms in Agular). Before proceeding to the main topic, let's take a look at forms and their types in Angular.

What are Forms in an Angular?

In Angular, forms are a key part of creating dynamic and interactive web applications. They allow users to enter data, submit it, and interact with the application's interface.

Types of Forms in Angular

Angular offers two main methods for working with forms:

  1. Template-driven forms: Template-driven forms are primarily created and managed in the component's template using directives such as ngModel and ngForm.
  2. Reactive forms: Reactive forms are created programmatically in the component class using form control objects.

What is Reactive Form in Angular?

Reactive forms in Angular provide a more programmatic and flexible approach to constructing forms compared to template-driven forms.

Using the reactive forms, you can define the form model and its behavior directly in the component class using the TypeScript language, which allows for greater control and customization options.

Note

Reactive forms are especially useful for complex forms or forms with dynamic behavior.

Prerequisites to Create Reactive Forms in Angular

The prerequisites to create reactive forms in Angular are:

  • FormGroup: A FormGroup is a collection of form controls that represents the entire form structure and holds the current value and state of each form control.
    You create a FormGroup by instantiating the FormGroup class in the component class.
  • FormControl: A FormControl represents an individual form control, such as an input field or a select dropdown. It holds the current value and validation state of the control.
    You create a FormControl by instantiating the FormControl class in the component class.
  • FormBuilder: The FormBuilder service offers easy-to-use methods for creating instances of FormGroup and FormControl.
    It simplifies the process of creating reactive forms by abstracting some of the boilerplate code.
    You can inject the FormBuilder service into the component constructor and use it to create form controls and groups.

Except for the important points mentioned above, we also have additional elements of reactive forms such as validators and formArray, which are not necessary to discuss.

How to Add a Single FormControl to Reactive Form?

Users will enter their name or any similar value into an input field. The form will capture that input value and display the current value of the form control element.

To add a single FormControl, follow the following steps:

1. Register the reactive forms module

You need to register or import the "ReactiveFormsModule" into your 'NgModules' imports array as follows:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AgePipePipe } from './pipes/age-pipe.pipe';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
 declarations: [
   AppComponent,
   AgePipePipe,
 ],
 imports: [
   BrowserModule,
   AppRoutingModule,
   ReactiveFormsModule
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }

2. Import the necessary module

Ensure that all necessary modules are imported into your app.component.ts file and injected into the constructor. This typically includes FormBuilder and FormGroup from @angular/forms.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent implements OnInit{
 constructor(private fb: FormBuilder){

 }
 myForm: FormGroup = new FormGroup({});
 ngOnInit(): void {
   this.myForm = this.fb.group({
     'name': new FormControl(''),
   });
 }
}

3. Attach the form control to the template

Make sure that the formGroup and formControl should be attached to your template.

<form [formGroup] = "myForm">
 <input type="text" placeholder="Name" formControlName = "name">
 <button>Submit</button>
</form>

How to Add Multiple FormControl in Reactive Form?

If you are familiar with reactive forms, adding a single form control to your reactive forms is very easy. Simply follow the steps mentioned above and attach multiple FormControls instead of just one.

app.component.ts file

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent implements OnInit{
constructor(private fb: FormBuilder){

}
myForm: FormGroup = new FormGroup({});
ngOnInit(): void {
 this.myForm = this.fb.group({
   'name': new FormControl(''),
   'email': new FormControl(''),
   'city': new FormControl(''),
   'mobile': new FormControl(''),
 });
}
}

app.component.html file

<form [formGroup] = "myForm">
 <input type="text" formControlName = "name" placeholder="Name">
 <input type="text" formControlName = "email" placeholder="Email">
 <input type="text" formControlName = "city" placeholder="City">
 <input type="text" formControlName = "mobile" placeholder="Mobile">
 <button>Submit</button>
</form>

How to Use Validators in Angular Reactive Form?

Using validators in Angular reactive forms means applying validation rules to form controls. Angular offers built-in validators that can be used out of the box, and you can also create custom validators to meet specific needs.

Example

Let's see the following code to understand how to use the built-in validators in Angular Reactive Forms.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent implements OnInit{
constructor(private fb: FormBuilder){

}
myForm: FormGroup = new FormGroup({});
ngOnInit(): void {
 this.myForm = this.fb.group({
   'name': new FormControl('', [Validators.required, Validators.minLength(6)]),
   'email': new FormControl('', [Validators.required, Validators.email]),
   'city': new FormControl('', [Validators.required]),
   'mobile': new FormControl('', [Validators.minLength(10), Validators.maxLength(10)]),
 });
}
}

Conclusion

In conclusion, Angular's reactive forms offer a strong and valuable solution for building complex and dynamic forms in web applications.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.