Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement responsive form in angular

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article is about how to implement responsive forms in angular. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Responsive form

Angular provides two different ways to handle user input through forms: responsive forms and template-driven forms. [recommended for related tutorials: "angular tutorial"]

Responsive forms: provide direct, explicit access to the underlying form object model. They are more robust than template-driven forms. If forms are a key part of your application, or if you are already using responsive forms to build your application, use responsive forms.

Template-driven forms: rely on the instructions in the template to create and manipulate the underlying object model. They are useful for adding a simple form to an application, such as an email list registration form.

Only responsive forms are introduced here. For template-driven forms, please refer to the official website:

Https://angular.cn/guide/forms-overview#setup-in-template-driven-forms

Global registration responsive form module ReactiveFormsModule

To use a responsive form control, import ReactiveFormsModule from the @ angular/forms package and add it to your NgModule's imports array. As follows: app.module.ts

/ * app.module.ts * / import {ReactiveFormsModule} from'@ angular/forms';@NgModule ({imports: [/ / other imports... ReactiveFormsModule],}) export class AppModule {} add the underlying form control FormControl

There are three steps to using a form control.

Register the responsive form module in your application. This module declares some instructions that you want to use in the responsive form.

Generate a new instance of FormControl and save it in the component.

Register the FormControl in the template.

To register a form control, import the FormControl class and create a new instance of FormControl, saving it as a property of the class. As follows: test.component.ts

/ * test.component.ts * / import {Component} from'@ angular/core';import {FormControl} from'@ angular/forms' @ Component ({selector: 'app-name-editor', templateUrl:'. / name-editor.component.html', styleUrls: ['. / name-editor.component.css']}) export class TestComponent {/ / can set the initial value in the constructor of FormControl, which in this case is the empty string name = new FormControl ('');}

Then register the control in the template as follows: test.component.html

Name:

Name: {{name.value}}

For other properties and methods of FormControl, see the API reference manual.

Https://angular.cn/api/forms/FormControl#formcontrol

Group form controls into FormGroup

Just as an instance of FormControl allows you to control the controls corresponding to a single input box, an instance of FormGroup can track the form status of a set of FormControl instances, such as a form. When you create a FormGroup, each of these controls is tracked by its name.

Take a look at the following example: test.component.ts, test.component.html

Import {Component} from'@ angular/core' Import {FormControl, FormGroup, Validators} from'@ angular/forms'@Component ({selector: 'app-test', templateUrl:'. / test.component.html', styleUrls: ['. / test.component.css']}) export class TestComponent implements OnInit {constructor () {} profileForm = new FormGroup ({firstName: new FormControl ('', [Validators.required,Validators.pattern ('[a-zA-Z0-9] *')]), lastName: new FormControl ('' Validators.required),}) OnSubmit () {/ / View the value of each field in the control group console.log (this.profileForm.value)}} First Name: Last Name: Submit

{{profileForm.value}}

{{profileForm.status}}

{{profileForm.valid}}

{{profileForm.disabled}}

For other properties and methods of FormGroup, see the API reference manual.

Https://angular.cn/api/forms/FormGroup#formgroup

Generate control instances using simpler FormBuilder services

In responsive forms, when you need to deal with multiple forms, manually creating multiple instances of form controls can be tedious. FormBuilder services provide some convenient ways to generate form controls. FormBuilder uses the same method behind the scenes to create and return these instances, but it is easier to use.

FormBuilder is an injectable service provider that is provided by ReactiveFormModule. You can inject this dependency simply by adding it to the component's constructor.

FormBuilder services have three methods: control (), group (), and array (). These methods are factory methods that are used to generate FormControl, FormGroup, and FormArray in the component class, respectively.

Take a look at the following example: test.component.ts

Import {Component} from'@ angular/core';// 1, import FormBuilderimport {FormBuilder, Validators} from'@ angular/forms' @ Component ({selector: 'app-test', templateUrl:'. / test.component.html', styleUrls: ['. / test.component.css']}) export class TestComponent {/ / 2, inject FormBuilder service constructor (private fb: FormBuilder) {} ngOnInit () {} profileForm = this.fb.group ({firstName: [', [Validators.required, Validators.pattern ('[a-zA-Z0-9] *')]] LastName: [', Validators.required],}) / equivalent to / / profileForm = new FormGroup ({/ / firstName: new FormControl (', [Validators.required,Validators.pattern ('[a-zA-Z0-9] *')]), / / lastName: new FormControl (', Validators.required), / /}); onSubmit () {console.log (this.profileForm.value) console.log (this.profileForm)}}

By comparison, you can find that using FormBuilder services makes it easier to generate FormControl, FormGroup, and FormArray without having to manually new a new instance each time.

Form validator Validators

Complete API list of Validators class validators, refer to the API manual

Https://angular.cn/api/forms/Validators

The Validators function can be either synchronous or asynchronous.

Synchronization validators: these synchronization functions accept an instance of the control and return a set of validation errors or null. You can instantiate a FormControl as the second argument to the constructor.

Asynchronous validators: these asynchronous functions take an instance of the control and return a Promise or Observable, which later issues a set of validation errors or null. When you instantiate FormControl, you can pass them in as a third parameter.

For performance reasons, Angular will run asynchronous validators only after all synchronous validators have passed. These validation errors are set only after each asynchronous validator has been executed.

API of the validator Validators class

Https://angular.cn/api/forms/Validators

Class Validators {static min (min: number): ValidatorFn / / minimum allowed value static max (max: number): ValidatorFn / / maximum value static required (control: AbstractControl): ValidationErrors | null / / required static requiredTrue (control: AbstractControl): ValidationErrors | null static email (control: AbstractControl): ValidationErrors | null / / is the mailbox format static minLength (minLength: number): ValidatorFn / / minimum length static maxLength (maxLength: number): ValidatorFn / / maximum length static pattern (pattern: string | RegExp): ValidatorFn / / regular matching static nullValidator (control: AbstractControl): ValidationErrors | null / / do nothing static compose (validators: ValidatorFn []): ValidatorFn | null static composeAsync (validators: AsyncValidatorFn []): AsyncValidatorFn | null} built-in validator function

To use the built-in validator, you can add the

Import {Validators} from'@ angular/forms' ... ngOnInit (): void {this.heroForm = new FormGroup ({/ / instantiate the FormControl control name: new FormControl (this.hero.name, [Validators.required, / / verify) Required Validators.minLength (4), / / length not less than 4 forbiddenNameValidator (/ bob/i) / / Custom Validator]), alterEgo: new FormControl (this.hero.alterEgo), power: new FormControl (this.hero.power, Validators.required)}) } get name () {return this.heroForm.get ('name');} get power () {return this.heroForm.get (' power');} Custom Validator

For custom validators, please refer to the API manual.

Https://angular.cn/guide/form-validation

Sometimes the built-in validator does not meet the requirements very well, for example, we need to validate a form and require that the input value can only be the value in a certain array, and the value in this array changes in real time with the program running. at this time, the built-in validator can not meet this requirement, you need to create a custom validator.

Add a custom validator to the responsive form. In the built-in validator section above, there is a forbiddenNameValidator function as follows:

Import {Validators} from'@ angular/forms';...ngOnInit (): void {this.heroForm = new FormGroup ({name: new FormControl (this.hero.name, [Validators.required, Validators.minLength (4), / / 1, add custom validator forbiddenNameValidator (/ bob/i)])}) } / / 2. Implement a custom validator that forbids the input of values with bob strings export function forbiddenNameValidator (nameRe: RegExp): ValidatorFn {return (control: AbstractControl): ValidationErrors | null = > {const forbidden = nameRe.test (control.value); / / 3. Return null if the value is valid or return forbidden: {value: control.value}}: null;};}

The validator returns null if the value is valid, or a validation error object if it is invalid. Validation error objects usually have a property called validation key (forbiddenName). The value is an arbitrary dictionary that you can use to insert error messages ({name}).

Add a custom validator to the template-driven form. To add an instruction to the template, the instruction contains the validator function. At the same time, the directive needs to register itself as a provider of NG_VALIDATORS. As follows:

/ / 1. Import related classes import {NG_VALIDATORS, Validator, AbstractControl, ValidationErrors} from'@ angular/forms';import {Input} from'@ angular/core'@Directive ({selector:'[appForbiddenName]', / / 2, providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}]}) export class ForbiddenValidatorDirective implements Validator {@ Input ('appForbiddenName') forbiddenName ='' / / 3. Implement the validator interface, that is, implement the validate function validate (control: AbstractControl): ValidationErrors | null {/ / returns null if the value is valid, or return this.forbiddenName if it is invalid? ForbiddenNameValidator (new RegExp (this.forbiddenName,'i')) (control): null;}} / / 4. Custom verification function export function forbiddenNameValidator (nameRe: RegExp): ValidatorFn {return (control: AbstractControl): ValidationErrors | null = > {const forbidden = nameRe.test (control.value) / / 3. Return null if the value is valid, or return forbidden the validation error object if it is invalid? {forbiddenName: {value: control.value}}: null;};}

Note that custom validation instructions are instantiated using useExisting instead of useClass. If you use useClass instead of useExisting, a new class instance is registered, and it does not have a forbiddenName.

Thank you for reading! This is the end of the article on "how to implement a responsive form in angular". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report