SoFunction
Updated on 2025-04-08

Detailed steps to use responsive forms in Angular

Introduction

Angular provides two ways to process forms: template-driven forms and responsive forms (also known as model-driven forms). Template-driven forms are the default way to process forms in Angular. When using template-driven forms, template directives are used to build the internal representation of the form. When using responsive forms, you need to build your own form representation in the component class.

Here are some of the benefits of responsive forms:

  • Using a custom validator
  • Dynamically change verification rules
  • Dynamically add form fields

In this article, you will explore how to apply responsive forms to a sample Angular application.

Prerequisites

If you want to follow this article, you need:

  • Local installation, you can follow "How to Install and Create a Local Development Environment".

This article assumes that you have some basic knowledge of Angular.

This article also assumes that you are using@angular/cliThe generated brand new Angular project is built. If you are just starting out with the Angular CLI, you can refer to this article.

This tutorial has passed Node v15.1.0,npm v6.14.8、@angular/corev11.0.0 and@angular/formsVerification of v11.0.0.

Step 1 ——Set the project

For the purpose of this tutorial, you will use@angular/cliThe generated default Angular project begins to build.

npx @angular/cli new angular-reactive-forms-example --style=css --routing=false --skip-tests

This configures a new Angular project with the style set to "CSS" (rather than "Sass", "Less", or "Stylus", no routes, and tests are skipped.

Enter the newly created project directory:

cd angular-reactive-forms-example

To use responsive forms, you will useReactiveFormsModuleInsteadFormsModule

Open in your code editorAnd addReactiveFormsModule

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

So far, you should have a useReactiveFormsModuleThe new Angular project.

Step 2 - Add a form to the component template

When using responsive forms, the logic is declared entirely in the component class.

Open in your code editorAnd add the following code:

<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm)">
  <div>
    <label>
      Name:
      <input formControlName="name" placeholder="Your name">
    </label>
  </div>
  <div>
    <label>
      Email:
      <input formControlName="email" placeholder="Your email">
    </label>
  </div>
  <div>
    <label>
      Message:
      <input formControlName="message" placeholder="Your message">
    </label>
  </div>
  <button type="submit">Send</button>
</form>

This code will create a field containing three (nameemailandmessage) form. There will also be a labeled "Send""submit"button. When submitting the form, it will be calledonSubmit(myForm)method.

Let's break it down:

  • formGroup: Forms will be treated asFormGroup,thereforeformGroupDirectives allow a name to be assigned to the form group.
  • ngSubmit: This is an event that is fired when the form is submitted.
  • formControlName: Each form field should have oneformControlNameDirective whose value will be used in the component class.

By this point, you should already have a component template that uses the form.

Step 3 ——Build component classes

Next, in the component class, you will defineFormGroupandFormGroupEach of themFormControl

If in newFormControlA value is provided that will be used as the initial value of the field.

NoticeFormGroupandFormControlThe name of the same as the name used in the template. Also pay attention to how you arengOnInitInitialization in the life cycle hookFormGroup

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './',
  styleUrls: ['./']
})
export class AppComponent implements OnInit {
  myForm: FormGroup;
  ngOnInit() {
     = new FormGroup({
      name: new FormControl('Sammy'),
      email: new FormControl(''),
      message: new FormControl('')
    });
  }
  onSubmit(form: FormGroup) {
    ('Valid?', ); // true or false
    ('Name', );
    ('Email', );
    ('Message', );
  }
}

In this tutorial,onSubmitThe method does not actually pass the submitted form value to any external service or server. It is used to show how you access the validity of the form andFormControlvalue.

Until then, you can compile your application and open it in a web browser. InnameemailandmessageEnter the value and clickSubmitAfter that, the console log will display these values.

Step 4 — Update the component class to use FormBuilder

ngOnInitForm builds inFormBuilderRewrite the auxiliary program. This avoids newing of form groups and form controls.

Open in the code editor, removeFormControlUse togetherFormBuilderreplaceFormGroup

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './',
  styleUrls: ['./']
})
export class AppComponent implements OnInit {
  myForm: FormGroup;
  constructor(private fb: FormBuilder) {}
  ngOnInit() {
     = ({
      name: 'Sammy',
      email: '',
      message: ''
    });
  }
  onSubmit(form: FormGroup) {
    ('Valid?', ); // true or false
    ('Name', );
    ('Email', );
    ('Message', );
  }
}

useFormBuilderThis code reduces creationFormGroupboilerplate code.

Step 5 — Update the component class to use Validators

WillValidatorsAdd classes to your import and declare form controls using arrays instead of simple string values.

The first value in the array is the initial form value and the second value is the validator to be used. Note that multiple validators can be used on the same form control by wrapping them into an array.

Open in the code editor,Add toValidators

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-root',
  templateUrl: './',
  styleUrls: ['./']
})
export class AppComponent implements OnInit {
  myForm: FormGroup;
  constructor(private fb: FormBuilder) {}
  ngOnInit() {
     = ({
      name: ['Sammy', ],
      email: ['', [, ]],
      message: ['', [, (15)]],
    });
  }
  onSubmit(form: FormGroup) {
    ('Valid?', ); // true or false
    ('Name', );
    ('Email', );
    ('Message', );
  }
}

This code isnameemailandmessageField addedrequired. It also ensuresemailValues ​​are in the format of a valid email address. It also ensuresmessageValues ​​are at least 15 characters long.

If any of these form requirements fail,validThe value will befalse. If all these form requirements are passed,validThe value will betrue

Step 6 — Access form values ​​and validity in templates

In the template, each can be accessedFormControland the value and validity of the entire form group.

Open,use*ngIfTo display a feedback message, telling the user that the form value is invalid:

<form [formGroup]="myForm" (ngSubmit)="onSubmit(myForm)">
  <div>
    <label>
      Name:
      <input formControlName="name" placeholder="Your name">
    </label>
    <div *ngIf="('name').invalid && (('name').dirty || ('name').touched)">
      Please provide a name.
    </div>
  </div>
  <div>
    <label>
      Email:
      <input formControlName="email" placeholder="Your email">
    </label>
    <div *ngIf="('email').invalid && (('email').dirty || ('email').touched)">
      Please provide a valid email address.
    </div>
  </div>
  <div>
    <label>
      Message:
      <input formControlName="message" placeholder="Your message">
    </label>
    <div *ngIf="('message').invalid && (('message').dirty || ('message').touched)">
      Messages must be at least 15 characters long.
    </div>
  </div>
  <button type="submit" [disabled]="">Send</button>
</form>

This code checks whether the user interacts with the field (dirtyortouched). Then, if the value does not pass the verification requirement, it will display an error message.SendThe button will also be disabled before all issues with form values ​​are resolved.

There are several ways to retrieve the value of a form control. This example uses('name'), it is equivalent to. Available.hasError('required')or.Retrieve error message.

in conclusion

In this article, you explore how to apply responsive forms to a sample Angular application. You usedFormControlFormGroupFormBuilderandValidatorsTo build a sample form with validation. For more features, please refer to the official documentation.

If you want to learn more about Angular, check out our Angular topic page for relevant exercises and programming projects.

This is the end of this article about how to use responsive forms in Angular. For more related Angular responsive forms, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!