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/cli
The 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/core
v11.0.0 and@angular/forms
Verification of v11.0.0.
Step 1 ——Set the project
For the purpose of this tutorial, you will use@angular/cli
The 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 useReactiveFormsModule
InsteadFormsModule
。
Open in your code editorAnd add
ReactiveFormsModule
:
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 useReactiveFormsModule
The 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 (name
、email
andmessage
) 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
,thereforeformGroup
Directives 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 oneformControlName
Directive 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 defineFormGroup
andFormGroup
Each of themFormControl
。
If in newFormControl
A value is provided that will be used as the initial value of the field.
NoticeFormGroup
andFormControl
The name of the same as the name used in the template. Also pay attention to how you arengOnInit
Initialization 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,onSubmit
The 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 andFormControl
value.
Until then, you can compile your application and open it in a web browser. Inname
、email
andmessage
Enter the value and clickSubmitAfter that, the console log will display these values.
Step 4 — Update the component class to use FormBuilder
ngOnInit
Form builds inFormBuilder
Rewrite the auxiliary program. This avoids newing of form groups and form controls.
Open in the code editor, remove
FormControl
Use togetherFormBuilder
replaceFormGroup
:
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', ); } }
useFormBuilder
This code reduces creationFormGroup
boilerplate code.
Step 5 — Update the component class to use Validators
WillValidators
Add 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 to
Validators
:
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 isname
、email
andmessage
Field addedrequired
. It also ensuresemail
Values are in the format of a valid email address. It also ensuresmessage
Values are at least 15 characters long.
If any of these form requirements fail,valid
The value will befalse
. If all these form requirements are passed,valid
The value will betrue
。
Step 6 — Access form values and validity in templates
In the template, each can be accessedFormControl
and the value and validity of the entire form group.
Open,use
*ngIf
To 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 (dirty
ortouched
). 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 usedFormControl
、FormGroup
、FormBuilder
andValidators
To 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!