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

What are the two types of Form forms in Angular

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

Share

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

This article will explain in detail how the two types of Form forms in Angular are, and the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

In Angular, there are two types of forms, template-driven and model-driven.

1. Template drive

1.1 Overview

The control logic of the form is written in the component template and is suitable for simple form types.

1.2 get started quickly

Introduce dependency module FormsModule

Import {FormsModule} from "@ angular/forms" @ NgModule ({imports: [FormsModule],}) export class AppModule {}

Convert a DOM form to ngForm

Declare the form field as ngModel

Submit

Get the form field value

Import {NgForm} from "@ angular/forms" export class AppComponent {onSubmit (form: NgForm) {console.log (form.value)}}

Form grouping

Submit

1.3 form validation

Required fields for required

Minimum length of minlength field

Maximum length of maxlength field

Pattern validation rules for example: pattern= "\ d" matches a numeric value

Submit export class AppComponent {onSubmit (form: NgForm) {/ / check whether the form as a whole is verified to be submitted through console.log (form.valid)}}

Display the error message when the form item fails in the component template

Please fill in the user name that does not conform to the regular rules

Specifies the style when the form item fails validation

Input.ng-touched.ng-invalid {border: 2px solid red;}

two。 Model driven

2.1 Overview

The control logic of the form is written in the component class, has more control over the validation logic, and is suitable for complex form types.

In a model-driven form, the form field needs to be an instance of the FormControl class, and the instance object can verify the value in the form field, whether the value has been modified, and so on.

A set of form fields make up the entire form, which needs to be an instance of the FormGroup class, which can validate the form as a whole.

FormControl: a form item in a form group

FormGroup: form group, where the form is at least one FormGroup

FormArray: for complex forms, you can dynamically add form items or form groups. During form validation, one item in FormArray fails, and the whole fails.

2.2 getting started quickly

Introduction of ReactiveFormsModule

Import {ReactiveFormsModule} from "@ angular/forms" @ NgModule ({imports: [ReactiveFormsModule]}) export class AppModule {}

Create a FormGroup form control object in a component class

Import {FormControl, FormGroup} from "@ angular/forms" export class AppComponent {contactForm: FormGroup = new FormGroup ({name: new FormControl (), phone: new FormControl ()})}

Forms in associated component templates

Submit

Get form value

Export class AppComponent {onSubmit () {console.log (this.contactForm.value)}}

Set form default values

ContactForm: FormGroup = new FormGroup ({name: new FormControl ("default"), phone: new FormControl (15888888888)})

Form grouping

ContactForm: FormGroup = new FormGroup ({fullName: new FormGroup ({firstName: new FormControl (), lastName: new FormControl ()}), phone: new FormControl ()) submit onSubmit () {console.log (this.contactForm.value.name.username) console.log (this.contactForm.get (["name", "username"])? .value)}

2.3 FormArray

Requirements: a set of contact information is displayed by default on the page. You can add more contact groups by clicking the button.

Import {Component, OnInit} from "@ angular/core" import {FormArray, FormControl, FormGroup} from "@ angular/forms" @ Component ({selector: "app-root", templateUrl: ". / app.component.html" Styles: []}) export class AppComponent implements OnInit {/ / form contactForm: FormGroup = new FormGroup ({contacts: new FormArray ([])}) get contacts () {return this.contactForm.get ("contacts") as FormArray} / / add contact addContact () {/ / contact const myContact: FormGroup = new FormGroup ({name: new FormControl (), address: new FormControl () Phone: new FormControl ()}) / / add contact information this.contacts.push (myContact)} / / delete contact information removeContact (I: number) {this.contacts.removeAt (I)} ngOnInit () {/ / add default contact method this.addContact ()} onSubmit () {console.log (this.contactForm. Value)}} Delete contact information add contact information submission

2.4 built-in form validator

Validate form fields using the validation rules provided by the built-in validator

Import {FormControl, FormGroup, Validators} from "@ angular/forms" contactForm: FormGroup = new FormGroup ({name: new FormControl ("default", [Validators.required, Validators.minLength (2)])})

Gets whether the overall form is validated

OnSubmit () {console.log (this.contactForm.valid)} submit

Error message displayed as validation passed in the component template

Get name () {return this.contactForm.get ("name")!} Please fill in the name length cannot be greater than {{name.errors.maxlength.requiredLength}} the actual length is {{name.errors.maxlength.actualLength}}

2.5 Custom synchronized form Validator

The type of custom validator is TypeScript class

Class contains specific validation methods, which must be static methods

The validation method has one parameter, control, of type AbstractControl. Is actually the type of the instance object of the FormControl class

If the verification is successful, return null

If the verification fails, the object is returned. The property in the object is the verification identity, and the value is true, indicating that the verification failed.

The return value of the verification method is ValidationErrors | null

Import {AbstractControl, ValidationErrors} from "@ angular/forms" export class NameValidators {/ / cannot contain spaces static cannotContainSpace (control: AbstractControl): ValidationErrors | null {/ / verify that if (/\ s/.test (control.value)) return {cannotContainSpace: true} / verify passed return null} import {NameValidators} from ". / Name.validators" contactForm: FormGroup = new FormGroup ({name: new FormControl ("", [Validators.required) " NameValidators.cannotContainSpace])}) names cannot contain spaces

2.6 Custom Asynchronous form Validator

Import {AbstractControl, ValidationErrors} from "@ angular/forms" export class NameValidators {static shouldBeUnique (control: AbstractControl): Promise {return new Promise (resolve = > {if (control.value = = "admin") {resolve ({shouldBeUnique: true})} else {resolve (null)} contactForm: FormGroup = new FormGroup ({name: new FormControl ("", [Validators.required]) NameValidators.shouldBeUnique)}) duplicate user name is detecting whether the name is duplicated

2.7 FormBuilder

Create a shortcut to the form.

This.fb.control: form item

This.fb.group: form group, where the form is at least one FormGroup

This.fb.array: for complex forms, you can dynamically add form items or form groups. During form validation, one item in FormArray fails, and the whole fails.

2.8 exercise

Gets the selected values in a set of check boxes

{{item.name}} submit import {Component} from "@ angular/core" import {FormArray, FormBuilder, FormGroup} from "@ angular/forms" interface Data {name: string value: string} @ Component ({selector: "app-checkbox", templateUrl: ". / checkbox.component.html", styles: []}) export class CheckboxComponent {Data: Array = [{name: "Pear", value: "pear"}, {name: "Plum", value: "plum"} {name: "Kiwi", value: "kiwi"}, {name: "Apple", value: "apple"}, {name: "Lime" Value: "lime"}] form: FormGroup constructor (private fb: FormBuilder) {this.form = this.fb.group ({checkArray: this.fb.array ([])})} onChange (event: Event) {const target = event.target as HTMLInputElement const checked = target.checked const value = target.value const checkArray = this.form.get ("checkArray") as FormArray if (checked) {checkArray.push (this) .fb.control (value)} else {const index = checkArray.controls.findIndex (control = > control.value = value) checkArray.removeAt (index)}} onSubmit () {console.log (this.form.value)}}

Get the value selected in the radio box

Export class AppComponent {form: FormGroup constructor (public fb: FormBuilder) {this.form = this.fb.group ({gender: ""})} onSubmit () {console.log (this.form.value)}} Male Female Submit

2.9 other

PatchValue: set the value of the form control (you can set all of them, or you can set one of them, the others are not affected)

SetValue: set the value of the form control (set all, no one can be excluded)

ValueChanges: events that are triggered when the value of a form control changes

Reset: form content is empty

UpdateValueAndValidity: uncheck the specified input box

ValidateForm: FormGroup; this.validateForm.get ('cpwd'). UpdateValueAndValidity (); about how the two types of Form forms in Angular are shared here, I hope the above content can be of some help to you and learn more. 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