search
HomeWeb Front-endJS TutorialDeep dive into forms in Angular

Deep dive into forms in Angular

Apr 27, 2021 am 09:43 AM
angularform

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.

Deep dive into forms in Angular

Angular form


What is a template form

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.

What is a reactive form

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.

Responsive Form

Deep dive into forms in Angular

##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.

Form validation

Angular built-in validator

Angular provides us with several built-in validators, The following are the more commonly used validators:

    Validators.required - The form control value is not empty
  • Validators.email - The format of the form control value is email
  • Validators.minLength() - The minimum length of the form control value
  • Validators.maxLength() - The maximum length of the form control value
  • Validators.pattern() - The value of the form control must match the pattern corresponding Pattern (regular expression)

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(&#39;mobile的校验结果:&#39;, valid); 
   return of(valid ? null : { mobile: true }); 
 }

Angular Status Fields

    ##touched
  • and untouched
  • These two fields indicate whether the user has accessed the field, that is, whether this field has received focus. Generally used to determine whether form error messages are displayed. At the same time, if any field is touched, the touched attribute of the entire form is true; only when all fields are untouched, the untouched attribute of the entire form is true.
  • pristinedirty

如果一个字段的值从来没有改变过, 那么它的 pristine 就是 true, dirty 就是 false; 反之, 如果字段的值被修改过, 那么它的pristine 就是 false, dirty 就是 true。 同时, 如果任何一个字段是 dirty, 那么整个表单的 dirty 属性就是 true; 只有所有字段是 pristine 时, 整个表单的 pristine 属性才是 true。

  • pending

当一个字段处于异步校验时, 该字段的 pending 属性是 true。

自定义模板式表单的校验器

在Deep dive into forms in Angular里, 我们后台有一个编码的数据模型, 只需要将校验器的方法挂在指定字段属性上就可以了。 但是, 在模板式表单里, 后台是没有这类数据模型的, 指令才是唯一能用的东西, 所以我们需要将校验方法包装成指令, 然后才能在模板中使用它。

编写指令

@Directive({  
   selector: &#39;[mobile]&#39;, 
    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(&#39;required&#39;, &#39;username&#39;)">
      用户名是必填项!
    </div>  
    <div [hidden]="!myForm.form.hasError(&#39;minlength&#39;, &#39;username&#39;)">
      用户名长度至少是6位!
    </div>
</div>
// .ts文件中
usernameValid = true; 
usernameUntouched = true; 
onUsernameInput(form: NgForm): void {  
   if (form) {
      this.usernameValid = form.form.get(&#39;username&#39;).valid;    
      console.log(&#39;valid&#39;, this.usernameValid);          
      this.usernameUntouched = form.form.get(&#39;username&#39;).untouched;   
      console.log(&#39;untouched&#39;,   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!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor