search
HomeWeb Front-endJS TutorialAn article to talk about responsive forms in angular

An article to talk about responsive forms in angular

Jan 12, 2022 pm 06:58 PM
angularResponsive form

This article will talk about responsive forms in Angular, and introduce the methods of globally registering responsive form modules, adding basic form controls, and grouping form controls. I hope it will be helpful to everyone!

An article to talk about responsive forms in angular

Responsive Forms

Angular provides two different ways to handle user input through forms: Responsive Form and template driven form . [Related tutorial recommendations: "angular tutorial"]

  • Responsive form: Provides direct and explicit access to the underlying form object model. They are more robust than template-driven forms. If forms are a key part of your app, or you're already building your app using reactive forms, use reactive forms.
  • Template-driven forms: rely on instructions in templates to create and operate the underlying object model. They are useful for adding a simple form to your app, such as an email list signup form.

Only responsive forms are introduced here. For template-driven forms, please refer to the official website—https://angular.cn/guide/forms-overview#setup-in-template-driven-forms

Globally register the responsive form module ReactiveFormsModule

To use the responsive form control, you must import it from the @angular/forms package ReactiveFormsModule and add it to the imports array of your NgModule. As follows: app.module.ts

/***** app.module.ts *****/
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // other imports ...
    ReactiveFormsModule
  ],
})
export class AppModule { }

Add basic form control FormControl

There are three steps to use form control.

  • Register the reactive form module in your application. This module declares some directives that you want to use in reactive forms.

  • Generate a new FormControl instance and save it in the component.

  • Register this FormControl in the template.

To register a form control, import the FormControl class and create a new instance of FormControl, and save it as a property of the class . As follows: test.component.ts

/***** test.component.ts *****/
import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-name-editor',
  templateUrl: './name-editor.component.html',
  styleUrls: ['./name-editor.component.css']
})
export class TestComponent {
	// 可以在 FormControl 的构造函数设置初始值,这个例子中它是空字符串
  name = new FormControl('');
}

Then register the control in the template as follows: test.component.html

<!-- test.component.html -->
<label>
  Name: <input type="text" [formControl]="name">
</label>
<!-- input 中输入的值变化的话,这里显示的值也会跟着变化 -->
<p>name: {{ name.value }}</p>
## For other properties and methods of

#FormControl, please refer to the API reference manual:

https://angular.cn/api/forms/FormControl#formcontrol

Group form controls into FormGroup

Just like an instance of

FormControl allows you to control the control corresponding to a single input box, an instance of FormGroup also Ability to track the form state of a group of FormControl instances (such as a form). When a FormGroup is created, each control in it is tracked by its name.

Look at the following example demonstration:

test.component.tstest.component.html

import { Component } from &#39;@angular/core&#39;;
import { FormControl, FormGroup, Validators } from &#39;@angular/forms&#39;

@Component({
  selector: &#39;app-test&#39;,
  templateUrl: &#39;./test.component.html&#39;,
  styleUrls: [&#39;./test.component.css&#39;]
})
export class TestComponent implements OnInit {
    constructor() {}

    profileForm = new FormGroup({
      firstName: new FormControl(&#39;&#39;, [Validators.required,Validators.pattern(&#39;[a-zA-Z0-9]*&#39;)]),
      lastName: new FormControl(&#39;&#39;, Validators.required),
    });
	
	onSubmit() {
		// 查看控件组各字段的值
      console.log(this.profileForm.value)
    }
}
rrree

FormGroup For other properties and methods, please refer to the API reference manual:

https://angular.cn/api/forms/FormGroup#formgroup

Use a simpler FormBuilder Service generation control instance

In reactive forms, when you need to deal with multiple forms, manually creating multiple form control instances will be very tedious.

FormBuilderThe service provides some convenient methods to generate form controls. FormBuilderThe same way behind the scenes is used to create and return these instances, it's just simpler to use.

FormBuilder is an injectable service provider provided by ReactiveFormModule. This dependency can be injected by simply adding it to the component's constructor.

FormBuilder The service has three methods: control(), group() and array() . These methods are factory methods used to generate FormControl, FormGroup and FormArray respectively in the component class.

Look at the following example demonstration:

test.component.ts

<!-- profileForm 这个 FormGroup 通过 FormGroup 指令绑定到了 form 元素,在该模型和表单中的输入框之间创建了一个通讯层 -->
<!-- FormGroup 指令还会监听 form 元素发出的 submit 事件,并发出一个 ngSubmit 事件,让你可以绑定一个回调函数。 -->
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
    <label>
<!-- 由 FormControlName 指令把每个输入框和 FormGroup 中定义的表单控件 FormControl 绑定起来。这些表单控件会和相应的元素通讯 -->
      First Name: <input type="text" formControlName="firstName">
    </label>
    <label>
      Last Name: <input type="text" formControlName="lastName">
    </label>
    <button type="submit" [disabled]="!profileForm.valid">Submit</button>
  </form>

  <p>{{ profileForm.value }}</p>
  <!-- 控件组的状态: INVALID 或 VALID -->
  <p>{{ profileForm.status }}</p>	
  <!-- 控件组输入的值是否为有效值: true 或 false-->
  <p>{{ profileForm.valid }}</p>
  <!-- 是否禁用: true 或 false-->
  <p>{{ profileForm.disabled }}</p>

Comparison can be found that using the

FormBuilder service can more conveniently generate FormControl, FormGroup and FormArray instead of having to manually new a new instance every time.

Form ValidatorsValidators

Validators For a complete API list of class validators, refer to the API manual:

https://angular.cn/api/forms/Validators

The validator (

Validators) function can be a synchronous function or an asynchronous function.

  • 同步验证器:这些同步函数接受一个控件实例,然后返回一组验证错误或 null。你可以在实例化一个 FormControl 时把它作为构造函数的第二个参数传进去。
  • 异步验证器 :这些异步函数接受一个控件实例并返回一个 PromiseObservable,它稍后会发出一组验证错误或 null。在实例化 FormControl 时,可以把它们作为第三个参数传入。

出于性能方面的考虑,只有在所有同步验证器都通过之后,Angular 才会运行异步验证器。当每一个异步验证器都执行完之后,才会设置这些验证错误。

验证器Validators类的API

https://angular.cn/api/forms/Validators

class Validators {
  static min(min: number): ValidatorFn		// 允许输入的最小数值
  static max(max: number): ValidatorFn		// 最大数值
  static required(control: AbstractControl): ValidationErrors | null	// 是否必填
  static requiredTrue(control: AbstractControl): ValidationErrors | null
  static email(control: AbstractControl): ValidationErrors | null	// 是否为邮箱格式
  static minLength(minLength: number): ValidatorFn		// 最小长度
  static maxLength(maxLength: number): ValidatorFn		// 最大长度
  static pattern(pattern: string | RegExp): ValidatorFn	// 正则匹配
  static nullValidator(control: AbstractControl): ValidationErrors | null	// 什么也不做
  static compose(validators: ValidatorFn[]): ValidatorFn | null
  static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn | null
}

内置验证器函数

要使用内置验证器,可以在实例化FormControl控件的时候添加

import { Validators } from &#39;@angular/forms&#39;;
...
ngOnInit(): void {
  this.heroForm = new FormGroup({
  // 实例化 FormControl 控件
    name: new FormControl(this.hero.name, [
      Validators.required,	// 验证,必填
      Validators.minLength(4),	// 长度不小于4
      forbiddenNameValidator(/bob/i) // 自定义验证器
    ]),
    alterEgo: new FormControl(this.hero.alterEgo),
    power: new FormControl(this.hero.power, Validators.required)
  });
}
get name() { return this.heroForm.get(&#39;name&#39;); }

get power() { return this.heroForm.get(&#39;power&#39;); }

自定义验证器

自定义验证器的内容请参考 API手册:

https://angular.cn/guide/form-validation

有时候内置的验证器并不能很好的满足需求,比如,我们需要对一个表单进行验证,要求输入的值只能为某一个数组中的值,而这个数组中的值是随程序运行实时改变的,这个时候内置的验证器就无法满足这个需求,需要创建自定义验证器。

  • 在响应式表单中添加自定义验证器。在上面内置验证器一节中有一个forbiddenNameValidator函数如下:

    import { Validators } from &#39;@angular/forms&#39;;
    ...
    ngOnInit(): void {
      this.heroForm = new FormGroup({
        name: new FormControl(this.hero.name, [
          Validators.required,
          Validators.minLength(4),
          // 1、添加自定义验证器
          forbiddenNameValidator(/bob/i)
        ])
      });
    }
    // 2、实现自定义验证器,功能为禁止输入带有 bob 字符串的值
    export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
      return (control: AbstractControl): ValidationErrors | null => {
        const forbidden = nameRe.test(control.value);
        // 3、在值有效时返回 null,或无效时返回验证错误对象
        return forbidden ? {forbiddenName: {value: control.value}} : null;
      };
    }

    验证器在值有效时返回 null,或无效时返回验证错误对象。 验证错误对象通常有一个名为验证秘钥(forbiddenName)的属性。其值为一个任意词典,你可以用来插入错误信息({name})。

  • 在模板驱动表单中添加自定义验证器。要为模板添加一个指令,该指令包含了 validator 函数。同时,该指令需要把自己注册成为NG_VALIDATORS的提供者。如下所示:

    // 1、导入相关类
    import { NG_VALIDATORS, Validator, AbstractControl, ValidationErrors } from &#39;@angular/forms&#39;;
    import { Input } from &#39;@angular/core&#39;
    
    @Directive({
      selector: &#39;[appForbiddenName]&#39;,
      // 2、注册成为 NG_VALIDATORS 令牌的提供者
      providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}]
    })
    export class ForbiddenValidatorDirective implements Validator {
      @Input(&#39;appForbiddenName&#39;) forbiddenName = &#39;&#39;;
      // 3、实现 validator 接口,即实现 validate 函数
      validate(control: AbstractControl): ValidationErrors | null {
      	// 在值有效时返回 null,或无效时返回验证错误对象
        return this.forbiddenName ? forbiddenNameValidator(new RegExp(this.forbiddenName, &#39;i&#39;))(control)
                                  : null;
      }
    }
    // 4、自定义验证函数
    export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
      return (control: AbstractControl): ValidationErrors | null => {
        const forbidden = nameRe.test(control.value);
        // 3、在值有效时返回 null,或无效时返回验证错误对象
        return forbidden ? {forbiddenName: {value: control.value}} : null;
      };
    }

    注意,自定义验证指令是用 useExisting 而不是 useClass 来实例化的。如果用useClass来代替 useExisting,就会注册一个新的类实例,而它是没有forbiddenName 的。

    <input type="text" required appForbiddenName="bob" [(ngModel)]="hero.name">

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of An article to talk about responsive 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
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.