In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Most people do not understand the knowledge points of this article "what are the two types of forms of angular", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "what are the two types of forms of angular" article.
In Angular, there are two types of forms, template-driven and model-driven.
First, 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
1) introduce the dependency module FormsModule
Import {FormsModule} from "@ angular/forms" @ NgModule ({imports: [FormsModule],}) export class AppModule {}
2) convert DOM form to ngForm
3) declare the form field as ngModel
Submit
4), get the form field value
Import {NgForm} from "@ angular/forms" export class AppComponent {onSubmit (form: NgForm) {console.log (form.value) / / {username:''}
5), form grouping
Submit import {NgForm} from "@ angular/forms" export class AppComponent {onSubmit (form: NgForm) {console.log (form.value) / / {contact: {phone:'}, user: {username:'}
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)}}
Displays 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;} II. 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 validates 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. When the form is validated, one item in FormArray fails, and the whole fails.
2.2 getting started quickly
1), introduce ReactiveFormsModule
Import {ReactiveFormsModule} from "@ angular/forms" @ NgModule ({imports: [ReactiveFormsModule]}) export class AppModule {}
2) create a FormGroup form control object in the component class
Import {FormControl, FormGroup} from "@ angular/forms" export class AppComponent {contactForm: FormGroup = new FormGroup ({name: new FormControl (), phone: new FormControl ()})}
3), the form in the associated component template
Submit
4), get the form value
Export class AppComponent {onSubmit () {console.log (this.contactForm.value)}}
5), set the form default value
ContactForm: FormGroup = new FormGroup ({name: new FormControl ("default"), phone: new FormControl (15888888888)})
6), 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, and more contact groups can be added 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
1) 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)])})
2) get whether the overall form is verified
OnSubmit () {console.log (this.contactForm.valid)} submit
3). The error message displayed in the component template when the verification is passed
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" import {Observable} from "rxjs" 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. When the form is validated, one item in FormArray fails, and the whole fails.
Import {FormBuilder, FormGroup, Validators} from "@ angular/forms" export class AppComponent {contactForm: FormGroup constructor (private fb: FormBuilder) {this.contactForm = this.fb.group ({fullName: this.fb.group ({firstName: [", [Validators.required]], lastName: ["]}), phone: []})}}
2.8 listen for changes in form values
In practical work, we often need to deal with a form according to its worth changing. Generally, we can use ngModalChange or form to implement it.
2.8.1 ngModalChange
Import {FormControl, FormGroup} from "@ angular/forms" export class AppComponent {public name = 'a'; public nameChange () {}}
Angular officials do not recommend using ngModalChange.
2.8.2 form Control
Import {FormControl, FormGroup} from "@ angular/forms" export class AppComponent {contactForm: FormGroup = new FormGroup ({name: new FormControl ()}) ngOnInt () {this.contactForm.get ("name") .valueChanges.subscribe (data = > {console.log (data);}
2.9 exercise
1), get 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)}}
2), 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.10 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
The above is about the content of this article on "what are the two types of forms of angular". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.