Home > Article > Web Front-end > Deep dive into forms in Angular
This article will give you a detailed introduction to the forms in Angular. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
The data model of the form is defined through relevant instructions in the component template. Because when defining the data model of the form in this way, we will be limited by the syntax of HTML, so the template-driven method only Suitable for some simple scenes.
Reactive forms provide a model-driven way to process form inputs whose values change over time. When using reactive forms, you create an underlying data model by writing TypeScript code instead of HTML code. After the model is defined, you use some specific instructions to connect the HTML elements on the template with the underlying data model.
Note:
The data model is not an arbitrary object, it is a specific class in the angular/forms module, such as FormControl, It consists of FormGroup, FormArray, etc. In templated forms, these classes cannot be accessed directly. [Related recommendation: "angular Tutorial"]
Responsive forms will not generate HTML for you, the template still needs to be written by yourself.
In a template form, you cannot access the classes related to the data model, and you can only get the final data of the form; in a responsive form, you can access the classes related to the data model. , but since they are non-referenceable, they cannot be manipulated in templates, only in TypeScript code.
##FormGroup
FormGroup It can represent either part of the form or the entire form. It is a collection of multiple FormControls. FormGroup aggregates the values and status of multiple FormControl together. During form validation, if one FormControl in the FormGroup is invalid, the entire FormGroup will be invalid.FormControl
FormControl is the basic unit that constitutes a form. It is usually used to represent an input element, but it can also be used to represent a more complex component, such as Calendar, drop down selection box. FormControl saves the current value of the HTML element associated with it, the validation status of the element, and information such as whether the element has been modified.FormArray
FormArray is similar to FormGroup, but it has a length property. Generally speaking, FormGroup is used to represent the entire form or a fixed subset of form fields; FormArray is usually used to represent a set of fields that can grow.Angular built-in validator
Angular provides us with several built-in validators, The following are the more commonly used validators:Custom responsive form validator
In actual development, in order to meet the needs of the project, we need Customize some validators. Under normal circumstances, the verification function can be defined in the following form:xxxxValidator(control: AbstarctControl): {[key: string]: any} { // TODO 编写校验规则 return null; }The following takes a common registration page as an example:
Initialization form
ngOnInit(): void { this.formModel = this.fb.group({ username: ['', [Validators.required, Validators.minLength(6)]], // 密码 passwordsGroup: this.fb.group({ password: [''], passwordConfirm: [''] }, { validator: this.equalValidator }), // 手机号 mobile: ['', this.moblieValidator] }); }
Writing Validator
// 手机号码校验 moblieValidator(control: AbstractControl): any { const reg = /^((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8}$/; const valid = reg.test(control.value); console.log('mobile的校验结果:', valid); return valid ? null : { mobile: true }; } // 密码校验 equalValidator(group: FormGroup): any { const password = group.get('password') as FormControl; const passwordConfirm = group.get('passwordConfirm') as FormControl; const valid = password.value === passwordConfirm.value; console.log('密码校验结果', valid); return valid ? null : { equal: true }; }
Angular Asynchronous Validator
Angular’s form API also supports asynchronous validator, asynchronous validator Remote services can be called to check the values of form fields. The asynchronous validator is similar to the ordinary validator and is also a method. The only difference is that the asynchronous validator returns not an object but an observable stream.moblieAsyncValidator(control: AbstractControl): Observable<any> { const reg = /^((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8}$/; const valid = reg.test(control.value); console.log('mobile的校验结果:', valid); return of(valid ? null : { mobile: true }); }
Angular Status Fields
如果一个字段的值从来没有改变过, 那么它的 pristine 就是 true, dirty 就是 false; 反之, 如果字段的值被修改过, 那么它的pristine 就是 false, dirty 就是 true。 同时, 如果任何一个字段是 dirty, 那么整个表单的 dirty 属性就是 true; 只有所有字段是 pristine 时, 整个表单的 pristine 属性才是 true。
当一个字段处于异步校验时, 该字段的 pending 属性是 true。
在Deep dive into forms in Angular里, 我们后台有一个编码的数据模型, 只需要将校验器的方法挂在指定字段属性上就可以了。 但是, 在模板式表单里, 后台是没有这类数据模型的, 指令才是唯一能用的东西, 所以我们需要将校验方法包装成指令, 然后才能在模板中使用它。
编写指令
@Directive({ selector: '[mobile]', providers: [{provide: NG_VALIDATORS, useValue: moblieValidator, multi: true}]}) export class MobileValidatorDirective { constructor() { } } // html中引用 <div> 手机号:<input ngModel type="number" name="mobile" mobile required></div>
mutli: true
:指的是在 NG_VALIDATORS
这个 Token
下可以挂不同 useValue
属性所表示的值。
注意: 在模板式表单中, 是不可以在模板中使用字段的状态属性的。 模板式表单与Deep dive into forms in Angular不同, 它的模型的值和它状态的变更是异步的, 而且很难控制。
如果想要使用字段的状态属性,我们可以进行如下操作:
// .html文件中 <div> 用户名:<input ngModel type="text" minlength="6" name="username" (input)="onUsernameInput(myForm)" required> </div> <div [hidden]="usernameValid || usernameUntouched"> <div [hidden]="!myForm.form.hasError('required', 'username')"> 用户名是必填项! </div> <div [hidden]="!myForm.form.hasError('minlength', 'username')"> 用户名长度至少是6位! </div> </div> // .ts文件中 usernameValid = true; usernameUntouched = true; onUsernameInput(form: NgForm): void { if (form) { this.usernameValid = form.form.get('username').valid; console.log('valid', this.usernameValid); this.usernameUntouched = form.form.get('username').untouched; console.log('untouched', this.usernameUntouched); } }
小结: 在使用字段的状态属性时, Deep dive into forms in Angular比模板式表单更方便,可以节省很多代码,而且比较可控。所以模板式表单适合用于一些简单的场景。
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of Deep dive into forms in Angular. For more information, please follow other related articles on the PHP Chinese website!