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 realize the responsive form and template driver in angular

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to realize the responsiveness and template driver of forms in angular". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to realize the responsiveness and template driver of forms in angular.

I. brief introduction of angular form

Angular provides two different ways to handle user input through forms: responsive forms and template-driven forms. Both capture user input events from the view, validate user input, create a form model, modify the data model, and provide ways to track these changes.

1.1 differences between responsive forms and template-driven forms

Responsive forms provide direct and explicit access to the underlying form object model. They are more robust than template-driven forms: they are more extensible, reusable, and testable. 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. They are easy to add to applications, but they are not as extensible as responsive forms. If you have very basic form requirements and logic that can be managed only in templates, then template-driven forms are appropriate.

Responsive template-driven form modeling explicit, implicit in component classes, data model created by instructions structured and immutable unstructured and variable synchronous asynchronous form validation function instruction 1.2 build form model

Both responsive and template-driven forms track changes in values between the form input elements that the user interacts with and the form data in the component model. The two methods share the same set of underlying building blocks, but differ only in how to create and manage instances of common form controls.

1.3 Common form basic classes

Both responsive and template-driven forms are based on the following basic classes.

The FormControl instance is used to track the value and validation status of a single form control.

FormGroup is used to track the value and status of a group of form controls.

FormArray is used to track the values and status of an array of form controls.

ControlValueAccessor is used to create a bridge between the FormControl instance of Angular and the native DOM element.

II. Responsive form

Responsive forms use explicit, immutable ways to manage the state of the form at a specific point in time. Each change to the form state returns a new state, which maintains the integrity of the model as it changes. Responsive forms are built around Observable streams, and the input and values of the form are provided through a stream of these input values, which can be accessed synchronously.

2.1 add basic form controls

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 use a responsive form control, import ReactiveFormsModule from the @ angular/forms package and add it to your NgModule's imports array.

Import {ReactiveFormsModule} from'@ angular/forms';@NgModule ({imports: [/ / other imports... ReactiveFormsModule],}) export class AppModule {}

To register a form control, import the FormControl class and create a new instance of FormControl, saving it as a property of the class.

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 NameEditorComponent {name = new FormControl ('');}

You can use the constructor of FormControl to set the initial value, which in this case is an empty string. By creating these controls in your component class, you can directly monitor, modify, and verify the state of the form control.

After you create a control in a component class, you also associate it with a form control in the template. Modify the template to add formControl bindings to the form controls, and the formControl is provided by FormControlDirective in ReactiveFormsModule.

Name: 2.2 display the value of the form control

You can display its value in the following ways:

With the observable object valueChanges, you can use the AsyncPipe in the template or the subscribe () method in the component class to listen for changes in the form value.

Use the value property. It allows you to get a snapshot of the current value.

Name:

Value: {{name.value}}

Public name = new FormControl ('test'); public testValueChange () {this.name.valueChanges.subscribe ({next: value = > {console.log ("name value is:" + value);}})} 2.3 replace the value of the form control

Responsive forms also have some ways to programmatically modify the value of a control, which gives you the flexibility to modify the value of the control without the need for user interaction. FormControl provides a setValue () method that modifies the value of the form control and validates the structure of the value corresponding to the structure of the control. For example, when you receive form data from a back-end API or service, you can use the setValue () method to replace the original value with the new value.

UpdateName () {this.name.setValue ('Nancy' + new Date (). GetTime ());}

Update Name

2.4 grouping form controls

A form usually contains several interrelated controls. Responsive forms provide two ways to group multiple related controls into the same input form.

A form group defines a form with a set of controls that you can manage together. The basics of form groups are discussed in this section. You can also create more complex forms by nesting form groups.

The form array defines a dynamic form that you can add and remove controls at run time. You can also create more complex forms by nesting form arrays

To add a form group to this component, perform the following steps.

Create an instance of FormGroup.

Associate the FormGroup model with the view.

Save the form data.

Create a property called profileForm in the component class and set it to a new instance of FormGroup. To initialize this FormGroup, provide the constructor with an object made up of controls, and each name in the object corresponds to the name of the form control.

Import {FormControl, FormGroup} from'@ angular/forms'; profileForm = new FormGroup ({firstName: new FormControl (''), lastName: new FormControl (''),}); / / you can get the whole value public onSubmit () {/ / TODO: Use EventEmitter with form value console.warn (this.profileForm.value) / / {firstName: ", lastName:"}} / / the whole observable object can get the value this.profileForm.valueChanges.subscribe with the help of valueChanges ({next: value = > {console.log ("name value is:" + JSON.stringify (value) / / dashboard.component.ts:53 name value is: {"firstName": "dddd", "lastName": "bb"}}) / / the value this.profileForm.get ('firstName') .valueChanges.subscribe ({next: value = > {console.log ("First Name is:" + value); / / First Name is: aa} can be obtained separately through a single control at a later stage.

Ps: this FormGroup provides its model value in the form of an object, which comes from the value of each control in the group. The FormGroup instance has the same properties (such as value, untouched) and methods (such as setValue ()) as the FormControl instance.

This form group can also track the state and changes of each of these controls, so if the state or value of one of the controls changes, the parent control will also issue a new state change or value change event. The model of the control group comes from all its members. After defining the model, you must update the template to reflect the model in the view.

First Name: Last Name: Submit2.5 creates nested form groups

A form group can accept both a single form control instance and other form group instances as its child controls. This makes complex form models easier to maintain and logically group them together.

To make a more complex form, follow these steps.

Create a nested form group

This nested form is grouped in the board.

To create a nested group in profileForm, add a nested address element to the instance of the form group.

Public profileForm = new FormGroup ({firstName: new FormControl (''), lastName: new FormControl (''), address: new FormGroup ({street: new FormControl (''), city: new FormControl (''), state: new FormControl (''), zip: new FormControl ('')}) / / the whole observable object this.profileForm.valueChanges.subscribe ({next: value = > {console.log ("name value is:" + JSON.stringify (value)); / / name value is: {"firstName": "," lastName ":", "address": {"street": "b", "city": "," state ":", "zip": ""}) can be obtained with the help of the whole observable object. / / the value this.profileForm.get ('firstName') .valueChanges.subscribe can be obtained separately through a later single control ({next: value = > {console.log ("First Name is:" + value);}}) / / you can get the entire value of a form group of form components this.profileForm.get ('address') .valueChanges.subscribe (({next: value = > {console.log (' address value is:'+ JSON.stringify (value)); / / address value is: {"street": "b", "city": "," state ":", "zip": ""})) / / you can get the value of a formcontrol instance of a form group of form components this.profileForm.get ('address'). Get (' street') .valueChanges.subscribe (({next: value = > {console.log ('street value is:' + value); / / street value is: B}}))

After you modify the model in the component class, you also modify the template to dock the FormGroup instance to its input elements.

First Name: Last Name: Address Street: City: State: Zip Code: Submit 2.6 updates part of the data model

When changing values that contain multiple FormGroup instances, you may want to update only part of the model rather than completely replace it.

There are two ways to update model values:

Use the setValue () method to set a new value for a single control. The setValue () method strictly follows the structure of the form group and replaces the value of the control as a whole.

Using the patchValue () method, you can replace the form model with any property defined in the object.

The rigorous checking of the setValue () method can help you catch errors in complex form nesting, while patchValue () may silently fail when it encounters those errors.

Only firstName and street have been modified in the public updateProfile () {/ / profileForm model. Note that the street is modified in the object of the address property. This structure is necessary because the patchValue () method updates the structure of the model. PatchValue () updates only those properties defined in the form model. This.profileForm.patchValue ({firstName: 'Nancy' + new Date (). GetTime (), address: {street:' 123 Drew Street' + new Date (). GetTime ()}); / / ERROR Error: Must supply a value for form control with name: 'lastName'. The / / setValue () method strictly follows the structure of the form group this.profileForm.setValue ({firstName: 'Nancy' + new Date (). GetTime (), address: {street:' 123 Drew Street' + new Date (). GetTime ()});} 2.7 create dynamic forms

FormArray is an alternative to FormGroup to manage any number of anonymous controls. Like a FormGroup instance, you can dynamically insert and remove controls into the FormArray, and the value and validation state of the FormArray instance are calculated based on its child controls. However, you don't need to define a name for each control as a key, so if you don't know the number of child controls in advance, this is a good choice.

To define a dynamic form, perform the following steps.

Import the FormArray class.

Define a FormArray control.

Use the getter method to access the FormArray control.

Display this form array in the template

Initialize a FormArray by defining a set of (zero to multiple) controls in an array. Add an aliases attribute to the profileForm and define it as a FormArray type.

Import {FormControl, FormGroup, FormArray} from'@ angular/forms'; public profileForm = new FormGroup ({firstName: new FormControl (''), lastName: new FormControl (''), address: new FormGroup ({street: new FormControl (''), city: new FormControl (''), state: new FormControl (''), zip: new FormControl ('')), aliases: new FormArray ([new FormControl ('1')]) Public aliases = (this.profileForm.get ('aliases')); public addAlias () {(this.profileForm.get (' aliases')) .push (new FormControl ('1'));} / / get the data of the entire formArray this.profileForm.get ('aliases') .valueChanges.subscribe ({next: value = > {console.log (' aliases values is:'+ JSON.stringify (value) / / aliases values is: ["1", "3"]}); / / get the data of a single formControl in formArray (this.profileForm.get ('aliases')). Controls [0] .valueChanges.subscribe ({next: value = > {console.log (' aliases [0] values is:'+ value); / / aliases [0] values is: 0}})

To add aliases to the form model, you must add it to the template for user input. Like the formGroupName provided by FormGroupNameDirective, FormArrayNameDirective uses formArrayName to establish a binding between this FormArray instance and the template

First Name: Last Name: Address Street: City: State: Zip Code: Aliases Add Alias Alias: 2.8Responsive form API summary class description all three form control classes of AbstractControl (FormControl, The abstract base class of FormGroup and FormArray. It provides some common behaviors and attributes. FormControl manages the value and validity state of individual form controls. It corresponds to the form control of HTML, such as or. FormGroup manages the values and validity status of a set of AbstractControl instances. The group's properties include its child controls. The top-level form in the component is FormGroup. FormArray manages the values and validity status of some AbstractControl instance arrays. FormBuilder is an injectable service that provides factory methods for creating control instances. Third, template-driven form

In template-driven forms, the form model is implicit, not explicit. Directs NgModel to create and manage a FormControl instance for the specified form element.

The following components implement the same input fields for a single control using a template-driven form.

Import {Component} from'@ angular/core';@Component ({selector: 'app-template-favorite-color', template: `FavoriteColor: `}) export class FavoriteColorComponent {favoriteColor =';} IV. Responsive form validation form input

Add validator functions directly to the form control model (FormControl) in the component class. Then, once the control changes, Angular calls these functions.

4.1 verifier (Validator) function

The validator function can be 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.

4.2 built-in validator function

Built-in validators that are used as attributes in template-driven forms, such as required and minlength, can also be used as functions in the Validators class

Public profileForm = new FormGroup ({firstName: new FormControl ('', [Validators.required]),}); this.profileForm.get ('firstName'). ValueChanges.subscribe ({next: value = > {console.log ("First Name is:" + value); console.log (this.profileForm.get (' firstName') .errors); / / {required: true} | null}}) First Name: Name is required. 4.3 define a custom validator

The built-in validator does not always exactly match the use case in the application, so sometimes you need to create a custom validator.

Public profileForm = new FormGroup ({firstName: new FormControl ('', [Validators.required, this.forbiddenNameValidator (/ bob/i)])}); public forbiddenNameValidator (nameRe: RegExp): ValidatorFn {return (control: AbstractControl): {[key: string]: any} | null = > {const forbidden = nameRe.test (control.value); return forbidden? {forbiddenName: {value: control.value}: null;} } get firstName () {return this.profileForm.get ('firstName');} this.profileForm.get (' firstName'). ValueChanges.subscribe ({next: value = > {console.log ("First Name is:" + value); / / First Name is: bob console.log (JSON.stringify (this.profileForm.get ('firstName') .errors)); / / {"forbiddenName": {"value": "bob"}} | null}}) 4.4 Cross-field cross-validation

The cross-field cross-validator is a custom validator that compares the values of different fields in the form and accepts or rejects their combinations.

The following cross-validation examples illustrate how to do the following:

Validate the input of a responsive form or template-driven form against the values of two sibling controls

When the user interacts with the form and validation fails, a descriptive error message is displayed

To evaluate these two controls in a single custom validator, you must perform validation in their common ancestor control: FormGroup. You can query its child controls in FormGroup so that you can compare their values. To add a validator to FormGroup, pass a new validator to its second parameter at creation time.

This.profileForm.valueChanges.subscribe ({next: value = > {console.log (JSON.stringify (this.profileForm.errors)); / / {"identityRevealed": true} | null}}); public profileForm = new FormGroup ({firstName: new FormControl ('', [Validators.required,]), lastName: new FormControl (''),}, {validators: this.identityRevealedValidator}) Public identityRevealedValidator (control: FormGroup): ValidationErrors | null {const firstName = control.get ('firstName'); const lastName = control.get (' lastName'); return firstName & & lastName & & firstName.value = lastName.value? {identityRevealed: true}: null;}; 4.5 create an asynchronous validator

The asynchronous validator implements the AsyncValidatorFn and AsyncValidator interfaces. They are very similar to their synchronized versions, but with the following differences.

The validate () function must return a Promise or observable object

The returned observable object must be exhaustive, which means it must be completed at some point (complete). To convert endless observable objects into endless ones, you can add filter operators such as first, last, take, or takeUntil to the pipeline.

Asynchronous validation does not occur until the synchronous verification is complete and is performed only if the synchronous verification is successful. If a more basic validation method has found invalid input, this check order allows the form to avoid using expensive asynchronous validation processes (such as HTTP requests).

Trigger a formControlName let formControl = this.profileForm.get ('firstName'); formControl.updateValueAndValidity (); at this point, I believe you have a better understanding of how to implement the responsive form and template driver in angular, so you might as well do it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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