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 use responsive forms in Angular

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

Share

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

This article introduces the relevant knowledge of "how to use responsive forms in Angular". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

I. the basic concept of responsive form

1.FormControl 、 FormArray 、 FormGroup

1.FormControl: used to track the value and validation status of a single form control, such as a field binding

/ / initialize a field whose value is the test name, and const Name:FormControl = new FormControl is not available ({value:' test name', disabled: true})

2.FormArray: used to track the values and status of an array of form controls, such as several fields together, a common table, or embedding a table in a form

/ / FormArray this.validateForm = this.fb.group that defines the property of the form object as aliases ({aliases: this.fb.array ([]),}); / / get FormArray get aliases () {return this.validateForm.get ('aliases') as FormArray;} / / add itemthis.aliases.push to the FormArray (this.fb.group ({Id: 0PowerName: [null],}))

3.FormGroup: used to track the value and validation status of a single form control. It can contain single or multiple FormControl and FormArray. Generally, a form corresponds to an instance of FormGroup, while the fields of the form correspond to FormControl and FormArray. Of course, they can be nested within each other. For example, FormGroup can be nested in FormArray. This is its flexibility.

ValidateForm = new FormGroup ({Name: new FormControl ({value:' test name', disabled: true}),}); validateForm = this.fb.group ({})

4.FormBuilder: is an injectable service provider. It is very tedious to manually create multiple instances of form controls. FormBuilder services provide some convenient methods to generate form controls. In the past, each creation had to be FormGroup and then generated FormControl, while using FormBuilder's group method can reduce repetitive code. To put it bluntly, it is easy to generate forms.

ValidateFormless: FormGroup;// manually creates validateForm = new FormGroup ({Name: new FormControl ('test name'),}); / / FormBuilder form builder validateForm = this.fb.group ({Name: [{value:' test name', disabled:true}],})

2.Validator form validation

Form validation is used to ensure that the user's input is complete and correct. How to add a single validator to a form control, and how to display the overall state of the form, usually the validator returns null to indicate that all validations have passed.

1. Synchronization validator: the synchronization validator function accepts an instance of a control and then returns a set of validation errors or null, which can be passed in as a second parameter when instantiating FormControl

The value of / / formControlName must be consistent with the instance of FormControl in ts code / / to determine whether the corresponding FormControl fails the check and there is an error message Name is required. / / initialize a field and add the required validator const name:FormControl = new FormControl ({'test name', disabled: true}, Validators.required,); / / get the FormControlget name () {return this.heroForm.get ('name');}

two。 Asynchronous validator: the asynchronous function accepts an instance of the control and returns a Promise or Observable. Only after all synchronous validators have passed will Angular run the asynchronous validator, which can be passed as the third parameter when instantiating the FormControl.

3. Built-in validator: for example, validate some lengths, which cannot be empty and can be implemented using the Validator class that has been provided.

4. Custom validator: the validator provided within the system can not meet the existing requirements. You can use the custom validator to do some personalized verification. The custom validator must return a ValidationErrors type or empty.

The value of / / formControlName must be consistent with the instance of FormControl in ts code / / it is too long to judge whether the corresponding FormControl fails the check and there is an error message. / / initialize a field and add the required validator const name:FormControl = new FormControl ({'test name', disabled: true}, this.CustomValidators ()); CustomValidators () {return (control: AbstractControl): ValidationErrors | null = > {if (control.value.verifier 10) {return {Invalid:true}} return null;};}

3. Basic methods and attributes of forms and elements

Method

Method use effect setValue () use setVlue to set the value of the control FormControl, but when you use it, you must assign all the properties of FormGroup together, not individually. It is often used to modify load assignment. PatchValue () can also set the value of FormControl by using patchValue. You can set the specified FormControl as needed without all settings. It is commonly used to reset all states of the current control in updating a field value reset () FormControl. The use in FormGroup is to reset the contents of the form object. For example, the control is set to unavailable disabled,control.reset ({value: 'Drew', disabled: true}) MarkAsPristine () marks the value of the form control as unchanged. This method is mainly used when the form is reset, when its state pristine is truemarkAsDirty (), it marks the value of the form FormControl control as changed, and its state Dirty is trueupdateValueAndValidity () recalculates the value of the form FormControl control and validates the state setValidators () to set the validator to the form FormControl control. If you set more than one, set the form FormControl control to be unavailable with the array "setValidators ([v1Powerv2Powerv3])" disable (). Note that when FormControl is disabled, the normal value getValue () corresponding to the form will be empty. You can use getRawValue () to get the corresponding FormControl value enable () to enable the form FormControl control setting.

Attribute

Property description touched when the touched of the form FormControl control is true indicates that the control has been focused, and vice versa untouched when untouched is true indicates that the control has not been focused, and vice versa, pristine means that the form element is pure and the user has not operated it, and you can use the markAsPristine method to set it to truedirty to indicate that the form element has been manipulated by the user You can use the markAsDirty method to set to truestatus to get the state Errors on the form FormControl control to get the error message of the current control. Case analysis and application

1. Simple form implementation

# requirement 1

The main version of the framework we use is Angular 12 + NG-ZORRO, so many of the following implementations and sample code will be related to them. Although the code may be different, it is only slightly different at the UI level, but for TS code, it is just a change of clothes, just pay a little attention to it. In fact, the requirements in the following examples are basically some of the basic contents and problems that I need to do when I work. After consulting the data, the idea and process of solving the problem, and even the screenshot are exactly the same.

Implement the most basic form addition function and verify that the employee ID is required and the length cannot exceed 50. The effect to be achieved is as follows

Analysis.

1. First of all, there is no special attention to the requirements, basically a simple input box assignment and then save, as long as the basic concept is clear to achieve this kind of the simplest

two。 We can use one FormGroup and six FormControl to complete and bind the interface.

3. Binding validator is used to verify length and required

Implementation steps

1. Define the html form structure

Employee ID employee number is required

two。 Declare the form object in the TypeScript code, inject FormBuilder in the constructor, and initialize the form in ngOnInit

/ / define form object validateForm:FormGroup;// constructor injection FormBuilderconstructor (private fb: FormBuilder) {} / / initialize form ngOnInit () {/ / initialize and bind required validator and length validator this.validateForm = this.fb.group ({EmployeeID: [', [Validators.required, Validators.maxLength (50)],})}

two。 Apply a form to a table

Demand 2

Need to implement the form addition and submission of the form, as well as personalized customization requirements, to achieve the effect diagram and requirements are described as follows

1. Click Add to add a row of table, edit, click Save to save data, click Revoke to cancel editing

two。 The default start and end times are prohibited

3. When selecting Contract Type as "short-term contract" Contract start date and Contract end date are available, when selecting Contract Type as "long-term contract" is not available

4. If Contract start date and Contract end date are available, you need to verify the validity of the start and end time. For example, the start event cannot exceed the end time.

Analysis.

1. Use the form in the table. Although the form is in the table, each column is also a FormControl.

two。 A total of four columns need to enter a value, which means there are four FormControl, and the last column is two buttons.

3. According to the above basic knowledge, we know that FormControl cannot be used alone, so it needs to be wrapped in FormGroup. At this point, one line corresponds to a FormGroup.

4. As we know from a FormGroup corresponding to a row, our table has multiple rows, that is, there are multiple FormGroup, and we can use FormArray to store it, because it represents a set of form groups.

5. According to point 2 of the requirement, the default start time and end time are prohibited. We know that when initializing the start, we can set the FormControl corresponding to the start and end time to disabled.

6. The third requirement needs to involve linkage, that is, when the value of FormControl corresponding to Contract Type is "short-term contract", the FormControl corresponding to "start and end time" needs to be set to available, which needs to be done by custom validator.

Implementation steps

1. First define the Html form structure

Contract type Contract start date Contract end date Agreement item Operation The start time cannot be later than the end time The start time cannot be later than the end time Save Revoke

two。 Declare the form object validateForm in the TypeScript code, and then initialize an instance of the property aliases of type FormArray as the value of the table formArrayName

3. Add a piece of data to the property aliases of the form object validateForm when you click the Add button

4. Define a custom validator contractTypeValidation () method for Contract Type linkage

5. Define the timeValidation () method of the time verifier. If the time is invalid, set the error state of FormControl to the property beginGtendDate, and then choose whether to render Japanese information according to this property in the template.

/ / define form object validateForm:FormGroup;// constructor injection FormBuilderconstructor (private fb: FormBuilder) {} / / initialize a form object validateFormngOnInit () {this.validateForm = this.fb.group ({aliases: this.fb.array ([]),}) in the declaration period hook function;} / / declare that the aliases attribute is used as interface formArrayName binding get aliases () {return this.validateForm.get ('aliases') as FormArray } addNewRow () {const group = this.fb.group ({/ / add to Type initialization verifier Type: [null, [CommonValidators.required, this.contractTypeValidation ()]], / / initialize FormControl StartDate with StartDate and EndDate disabled: [{value: null, disabled: true}, []], EndDate: [{value: null, disabled: true}, []], ContractType: [null, [CommonValidators.required, CommonValidators.maxLength (20)]] }) this.aliases.push (group) } / / Custom Contract Type validator contractTypeValidation () {return (control: AbstractControl): ValidationErrors | null = > {let contents: any [] = this.validateForm.value.aliases; if (control.touched & &! control.pristine) {/ / get form group const formArray: any = this.validateForm.controls.aliases / / find the index const index = contents.findIndex ((x) = >! x.isShowEdit) of the row being edited; / / get the start and end time FormControl instance const StartDate: AbstractControl = formArray.controls [index] .get ('StartDate'), EndDate: AbstractControl = formArray.controls [index] .get (' EndDate') If (control.value = = "short-term contract") {/ / set a verifier for the start and end time to verify the validity of the time StartDate.setValidators ([CommonValidators.required, this.timeValidation ()]); EndDate.setValidators ([this.timeValidation ()]); / / start the start and end time control EndDate.enable (); StartDate.enable () } else {/ / Contract Type clears the verifier StartDate.clearValidators (); EndDate.clearValidators (); / / disables start and end time EndDate.disable (); StartDate.disable ();}} return null if it is not a short-term contract }} / / Custom time verifier timeValidation () {return (control: AbstractControl): ValidationErrors | null = > {if (! control.pristine) {let contents: any [] = this.validateForm.value.aliases; const formArray: any = this.validateForm.controls.aliases; const index = contents.findIndex ((x) = >! x.isShowEdit) / / get start and end time FormControl instance const EndDate: string = formArray.controls [index] .get ('EndDate'). Value; const StartDate: string = formArray.controls [index] .get (' StartDate') .value; if (EndDate = null | | StartDate = null) return null / / if the time is invalid, set the error state of the current control beginGtendDate to true if (Date.parse (control.value) > Date.parse (EndDate) | | Date.parse (control.value) < Date.parse (StartDate)) {return {beginGtendDate: true};}} return null This is the end of the content of "how to use responsive forms in Angular". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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