SoFunction
Updated on 2025-04-04

Implementation of responsive form in angular6

1: Introduce ReactiveFormsModule into the AppModule module

To use responsive forms, import the ReactiveFormsModule from the @angular/forms package and add it to your NgModule imports array.

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

@NgModule({
 imports: [
 // other imports ...
 ReactiveFormsModule
 ],
})
export class AppModule { }

2: Create a new component

ng g c NameEditor

3: Please import the FormControl class in the component

The FormControl class is the most basic fast construction of angular responsive forms. To register a single form control, please import the FormControl class in the component, create a new instance of FormControl, and save it in a certain property.

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
 selector: 'app-name-editor',
 templateUrl: './',
 styleUrls: ['./']
})

export class NameEditorComponent {
 name = new FormControl('');
} 

4: Register a form control in the component's template

Modify the template to add a formControl binding to the form control, which is provided by FormControlDirective in the ReactiveFormsModule.

<label>
 Name:
 <input type="text" [formControl]="name">
</label>

<p>
 Value: {{  }}
</p>

Using this template binding syntax, register the form control with the input element named name in the template. In this way, form controls and DOM
Elements can communicate with each other: the view will reflect the changes in the model, and the model will also reflect the changes in the view.

5: Replace the value of the form control

FormControl provides a setValue() method, which will modify the value of this form control.

js

 updateName() {
  ('Nancy');
 }

html

<label>
 Name:
 <input type="text" [formControl]="name">
</label>
<p>
 Value:{{}}
</p>
<p>
 <button (click)="updateName()">Update Name</button>
</p>

In this example, you only use a single control FormControl, but when the setValue() method of FormGroup or FormArray is called, the value passed in must match the structure of the control group or control array

6: Group form controls

The FormControl instance can control the controls corresponding to a single input box. FormGroup can control the form status of a group of FormControl instances. When creating a FormGroup, each control will be tracked according to the name.

1>: Create a new component

ng g c ProfileEditor

2>: Import the FormGroup and FormControl classes and create a FormGroup instance

import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
 
@Component({
 selector: 'app-profile-editor',
 templateUrl: './',
 styleUrls: ['./']
})

export class ProfileEditorComponent {
 profileForm = new FormGroup({
 firstName: new FormControl(''),
 lastName: new FormControl(''),
 });
}

Now these separate controls FormControl are collected into a control group. The FormGroup instance has the same properties (such as value, untouched) and methods (such as setValue()) as the FormControl instance.

3>: Associate the model and view of FormGroup

FormGroup can track the state and changes of each individual control FormControl. If the state or value of one of the controls changes, the parent control will also have a new state change or value change event.

<form [formGroup]="profileForm">
 
 <label>
 First Name:
 <input type="text" formControlName="firstName">
 </label>

 <label>
 Last Name:
 <input type="text" formControlName="lastName">
 </label>

</form>

profileForm binds to the form element through the [formGroup] directive, creating a communication layer between the model and the input box in the form. The formControlName property provided by the FormControlName directive binds each input box and the form controls defined in the FormGroup.

4>: Associate the model and view of FormGroup

html

 <form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
  <label>
  First Name:
  </label>
  <input type="text" formControlName="firstName">
 
  <label>
  Last Name:
  </label>
  <input type="text" formControlName="lastName">
 
  <button type="submit" >Submit</button>
 </form>

js

onSubmit () {
 ();
}

The submit event emitted by the form tag is a native DOM event. This event can be triggered by clicking a button of type submit

6: Nested form groups

js

profileForm = new FormGroup({
 firstName: new FormControl(''),
 lastName: new FormControl(''),
 address: new FormGroup({
  street: new FormControl(''),
  city: new FormControl(''),
  state: new FormControl(''),
  zip: new FormControl('')
 })
});

html

<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
 <label>
 First Name:
 </label>
 <input type="text" formControlName="firstName">
 <label>
 Last Name:
 </label>
 <input type="text" formControlName="lastName">

 <div formGroupName="address">
 <label>Streel</label>
 <input type="text" formControlName="street">
 <label>City</label>
 <input type="text" formControlName="city">
 <label>State</label>
 <input type="text" formControlName="state">
 <label>Zip Code</label>
 <input type="text" formControlName="zip">
 </div>

 <button type="submit" [disabled]="!">Submit</button>
</form>

Some model modifications

html

<button (click)="updateProfile()">Update Profile</button>

js

updateProfile() {
  ({
  firstName: 'Nancy',
  address: {
   street: '123 Drew Street'
  }
  });
}

The patchValue() method is to be updated for the structure of the model. patchValue() will only update those properties defined in the form model.

6: Use FormBuilder to generate form controls

The FormBuilder service provides some convenient ways to generate form controls.

FormBuilder uses the same way behind the scenes to create and return these instances, just to be easier to use. The ProfileEditor component will be refactored below and used FormBuilder to create these FormControls and FormGroups manually.

Step 1 - Import the FormBuilder class

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

Step 2 - Injecting the FormBuild service

constructor(private fb: FormBuilder) { }

Step 3- Generate form control

The FormBuilder service has three methods: control(), group() and array(). These methods are factory methods used to generate separately in component classes
FormControl, FormGroup, and FormArray.

You can use the group() method to define these properties with the same name as before. Here, the value corresponding to each control name is an array, and the first item in this array is its initial value. You can just use the initial value to define the control, but if your control also needs a synchronous or asynchronous validator, then the second item in this array

The third item provides synchronous and asynchronous validators.

import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';
 
@Component({
 selector: 'app-profile-editor',
 templateUrl: './',
 styleUrls: ['./']
})
export class ProfileEditorComponent {
 profileForm = ({
 firstName: ['open'],
 lastName: ['Ping'],
 address: ({
  street: [''],
  city: [''],
  state: [''],
  zip: ['']
 }),
 });
 
 constructor(private fb: FormBuilder) { }
}

7: Simple form verification

How to add a single validator to a form control and how to display the overall state of the form.

Step 1 - Importing Verifier Functions

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

Responsive forms contain a set of commonly used validator functions out of the box. These functions receive a control to verify and return an error object or null value based on the verification result.

Step 2 - Set the field as required

The most common checkpoint is to set a field as required. This section describes how to add a Required Validator to the firstName control.

In the component, set the static method to the second item in the firstName control value array.

profileForm = ({
 firstName: ['', ],
 lastName: [''],
 address: ({
 street: [''],
 city: [''],
 state: [''],
 zip: ['']
 }),
});

HTML5 has a set of built-in properties for native verification, including required, minlength, maxlength, etc. Although optional, you can also use them as additional properties on the input elements of the form. Here we add the required attribute to the firstName input element.

<input type="text" formControlName="firstName" required>

These HTML5 validator properties can be combined with the built-in validator provided by Angular responsive forms. Using these two validator practices in combination can prevent errors caused by the expression being modified again after the template is checked.

8: Display the status of the form

Now, you have added a required field to the form control, and its initial value is invalid. This invalid state bubbles into its parent FormGroup, which also makes the state of this FormGroup invalid. You can access the current state through the status property of the FormGroup instance.

<p>
 Form Status: {{  }}
</p>

9: Use form arrays to manage dynamic controls

FormArray is another option outside of FormGroup to manage any number of anonymous controls. FormArray is a good choice if you don't know the number of child controls in advance.

Step 1 - Import FormArray

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

Step 2 - Definition FormArray

Add an aliases property to profileForm and define it as the FormArray type. (The FormBuilder service is used to create a FormArray instance.)

profileForm = ({
 firstName: ['open', ],
 lastName: ['by'],
 address: ({
  street: [''],
  city: [''],
  state: [''],
  zip: ['']
 }),
 aliases: ([
  ('')
 ])
 });

Step 3 - Accessing the FormArray Control

Accessing controls through getters is more convenient and easy to reuse

Use getter syntax to create a class attribute called aliases

get aliases() {
 
}

The FormArray control that receives the nickname from the parent control FormGroup.

get aliases() {
 return ('aliases') as FormArray;
}
addAlias() {
 ((''));
}

Step 3 - Show form array in template

After defining the FormArray of aliases in the model, you must add it to the template for user input, use formArrayName in this
Create a binding between FormArray and the template.

<div formArrayName="aliases">
 <h3>Aliases</h3> <button (click)="addAlias()">Add Alias</button>

 <div *ngFor="let address of ; let i=index">
 <!-- The repeated alias template -->
 <label>
  Alias:
  <input type="text" [formControlName]="i">
 </label>
 </div>
</div>

Whenever a new alias is added, FormArray provides its control based on this index number. This will allow you to track each control every time the status and value of the root control is calculated.

All codes

html

<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
 <label>
 First Name:
 </label>
 <input type="text" formControlName="firstName" required>

 <label>
 Last Name:
 </label>
 <input type="text" formControlName="lastName">

 <div formGroupName="address">
 <h3>Address</h3>
 <label>Streel</label>
 <input type="text" formControlName="street">

 <label>City</label>
 <input type="text" formControlName="city">
 
 <label>State</label>
 <input type="text" formControlName="state">

 <label>Zip Code</label>
 <input type="text" formControlName="zip">
 </div>

 <div formArrayName="aliases">
 <h3>Aliases</h3>
 <button (click)="addAlias()">Add Alias</button>
 
 <div *ngFor="let address of ; let i=index">
  <label>Alias</label>
  <input type="text" [formControlName]="i" >
 </div>
 </div>

 <button type="submit" [disabled]="!">Submit</button>
 <p>
 <button (click)="updateProfile()">Update Profile</button>
 </p>

 <p>
 Form Status: {{  }}
 </p>
</form>

js

import { Component, OnInit } from '@angular/core';
import {FormControl, FormGroup, FormBuilder, Validators, FormArray} from '@angular/forms';

@Component({
 selector: 'app-profile-editor',
 templateUrl: './',
 styleUrls: ['./']
})
export class ProfileEditorComponent implements OnInit {
 profileForm = ({
 firstName: ['open', ],
 lastName: ['by'],
 address: ({
  street: [''],
  city: [''],
  state: [''],
  zip: ['']
 }),
 aliases: ([
  ('')
 ])
 });
 constructor(private fb: FormBuilder) {

 }

 ngOnInit() {
 }

 onSubmit () {
 ();
 }
 
 updateProfile() {
 ({
  firstName: 'Nancy',
  address: {
  street: '123 Drew Street'
  }
 });
 }
 get aliases () {
 return ('aliases') as FormArray;
 }
 addAlias() {
 ((''));
 }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.