Skip to content

11 Form

在 Angular 中,表单有两种类型,分别为Template-Driven Forms(模板驱动表单)和Reactive Forms(响应式表单,或称模型驱动表单).

11.1 Template-Driven

11.1.1 Overview

表单的控制逻辑写在组件模板中,适合简单的表单类型。

11.1.2 快速上手

  1. 引入依赖模块 FormsModule
import { FormsModule } from "@angular/forms"
@NgModule({
 imports: [FormsModule],
})
export class AppModule {}
  1. 将 DOM 表单转换为 ngForm
<form #f="ngForm" (submit)="onSubmit(f)"></form>
  1. 声明表单字段为 ngModel
<form #f="ngForm" (submit)="onSubmit(f)">
 <input type="text" name="username" ngModel/>
 <button>submit</button>
</form>
  1. 获取表单字段值
import { NgForm } from "@angular/forms"
export class AppComponent 1
 onSubmit(form: NgForm) {
     console.log(form.value)
 }
}

Screenshot 2025-01-18 at 21.14.41

Screenshot 2025-01-18 at 21.15.38

  1. 表单分组
<form #f="ngForm" (submit)="onSubmit (f)">
 <div ngModelGroup="user">
     <input type="text" name="username" ngModel />
 </div>
 <div ngModelGroup="contact">
     <input type="text" name="phone" ngModel />
   </div>
 <button>submit</button>
</form>

Screenshot 2025-01-18 at 22.14.39

Screenshot 2025-01-18 at 22.14.48

Screenshot 2025-01-18 at 22.15.21

11.1.3表单验证

  • required 必填字段
  • minlength 字段最小长度
  • maxlength 字段最大长度
  • pattern 验证正则 例如:pattern="\d”匹配一个数值
<form #f="ngForm" (submit)="onSubmit(f)">
    <input type="text" name="username" ngModel required pattern="\d" />
    <button>提交</button>
</form>
export class AppComponent {
    onSubmit (form: NgForm) {
        // 查看表单整体是否验证通过
    console. log (form.valid)
  }
}
<!-- 表单整体未通过验证时禁用提交表单 -->
<button type="submit" [disabled]="f.invalid">submit</button>

在组件模板中显示表单项未通过时的错误信息。

<form #f="ngForm" (submit)="onSubmit (f) ">
    <input #username="ngModel" />
    <div *ngIf="username.touched && !username valid && username.errors">
        <div *ngIf="username.errors.required">请填写用户名</div>
    <div *ngif="username.errors.pattern">不符合正则规则</div>
  </div>
</form>

指定表单项未通过验证时的样式。

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

Screenshot 2025-01-18 at 23.20.20

Screenshot 2025-01-18 at 23.19.57

Screenshot 2025-01-18 at 23.21.06

Screenshot 2025-01-18 at 23.21.16

Screenshot 2025-01-18 at 23.21.26

Screenshot 2025-01-18 at 23.27.16

Screenshot 2025-01-18 at 23.27.25

Screenshot 2025-01-18 at 23.31.56

Screenshot 2025-01-18 at 23.32.06

Screenshot 2025-01-18 at 23.36.07

Screenshot 2025-01-18 at 23.36.20

11.2 Reactive

11.2.1 Overview

表单的控制逻辑写在组件类中,对验证逻辑拥有更多的控制权,适合复杂的表单的类型。

在模型驱动表单中,表单字段需要是 FormControl 类的实例,实例对象可以验证表单字段中的值,值是否被修改过等等

Screenshot 2025-01-18 at 23.41.42

一组表单字段构成整个表单,整个表单需要是 FormGroup 类的实例,它可以对表单进行整体验证。

Screenshot 2025-01-18 at 23.46.04

  1. FormControl:表单组中的一个表单项
  2. FormGroup:表单组,表单至少是一个 FormGroup
  3. FormArray:用于复杂表单,可以动态添加表单项或表单组,在表单验证时,FormArray 中有一项没通过,整体没通过。

11.2.2 快速上手

  1. 引入 ReactiveFormsModule
import { ReactiveFormsModule } from "@angular/forms"

@NgModule ({
 imports: [ReactiveFormsModule]
} )

export class AppModule {}
  1. 在组件类中创建 FormGroup 表单控制对象
import { FormControl,    FormGroup } from "@angular/forms"

export class AppComponent {
 contactForm: FormGroup = new FormGroup ( {
     name: new FormControl(), 
    phone: new FormControl()
 })
}
  1. 关联组件模板中的表单
<form [formGroup]="contactForm" (submit)="onSubmit ()">
 <input type="text" formControlName="name" />
 <input type="text" formControlName="phone" />
  <button>
    submit
  </button>
</form>
  1. 获取表单值
// 导出一个类 
export class AppComponent {
  onSubmit() {
    console.log(this.contactForm.value) 
  }
}
  1. 设置表单default value
export class AppComponent {
  contactForm: FormGroup = new FormGroup({
    username: new FormControl("I am a default value"),
    phone: new FormControl(),
  })

  onSubmit() {
    console.log(this.contactForm.value) 
  }
}

Screenshot 2025-01-19 at 00.12.15

Screenshot 2025-01-19 at 00.12.26

Screenshot 2025-01-19 at 00.13.03

Screenshot 2025-01-19 at 00.13.08

11.2.3 FormArray

11.2.4 内置表单验证器

11.2.5 自定义同步表单验证器

11.2.6 自定义异步表单验证器

11.2.7 FormBuilder

创建表单的快捷方式。

  1. this.fb.control:表单项
  2. this.tb.group:表单组,表单至少是一个 FormGroup
  3. this.tb.array:用于复杂表单,可以动态添加表单项或表单组,在表单验证时,FormArray 中有一项没通过,整体没通过。
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: ["sam", [Validators.required]],
             lastName: [""]
            }),
            phone: []
            })
    }
}

Screenshot 2025-01-19 at 00.41.14

Screenshot 2025-01-19 at 00.41.22

11.2.8 Practice

11.2.9 其他