目录
一、模板驱动
二、模型驱动
首页 web前端 js教程 angular学习之聊聊两种类型的表单

angular学习之聊聊两种类型的表单

May 20, 2022 am 10:28 AM
angular angular.js

本篇文章带大家了解一下angular中的表单,了解一下两种类型的表单:模板驱动和模型驱动,希望对大家有所帮助!

angular学习之聊聊两种类型的表单

在 Angular 中,表单有两种类型,分别为模板驱动模型驱动。【相关教程推荐:《angular教程》】

一、模板驱动

1.1 概述

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

1.2 快速上手

1)、引入依赖模块 FormsModule

import { FormsModule } from "@angular/forms"

@NgModule({
  imports: [FormsModule],
})
export class AppModule {}
登录后复制

2)、将 DOM 表单转换为 ngForm

<form #f="ngForm" (submit)="onSubmit(f)"></form>
登录后复制

3)、声明表单字段为 ngModel

<form #f="ngForm" (submit)="onSubmit(f)">
  <input type="text" name="username" ngModel />
  <button>提交</button>
</form>
登录后复制

4)、获取表单字段值

import { NgForm } from "@angular/forms"

export class AppComponent {
  onSubmit(form: NgForm) {
    console.log(form.value) // {username: &#39;&#39;}
  }
}
登录后复制

5)、表单分组

<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>提交</button>
</form>
登录后复制
import { NgForm } from "@angular/forms"

export class AppComponent {
 onSubmit(form: NgForm) {
   console.log(form.value) // {contact: {phone: &#39;&#39;}, user:{username: &#39;&#39;}}
 }
}
登录后复制

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">提交</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;
}
登录后复制

二、模型驱动

2.1 概述

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

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

angular学习之聊聊两种类型的表单
一组表单字段构成整个表单,整个表单需要是 FormGroup 类的实例,它可以对表单进行整体验证。

angular学习之聊聊两种类型的表单

  • FormControl:表单组中的一个表单项

  • FormGroup:表单组,表单至少是一个 FormGroup

  • FormArray:用于复杂表单,可以动态添加表单项或表单组,在表单验证时,FormArray 中有一项没通过,整体没通过。

2.2 快速上手

1)、引入 ReactiveFormsModule

import { ReactiveFormsModule } from "@angular/forms"

@NgModule({
  imports: [ReactiveFormsModule]
})
export class AppModule {}
登录后复制

2)、在组件类中创建 FormGroup 表单控制对象

import { FormControl, FormGroup } from "@angular/forms"

export class AppComponent {
  contactForm: FormGroup = new FormGroup({
    name: new FormControl(),
    phone: new FormControl()
  })
}
登录后复制

3)、关联组件模板中的表单

<form [formGroup]="contactForm" (submit)="onSubmit()">
  <input type="text" formControlName="name" />
  <input type="text" formControlName="phone" />
  <button>提交</button>
</form>
登录后复制

4)、获取表单值

export class AppComponent {
  onSubmit() {
    console.log(this.contactForm.value)
  }
}
登录后复制

5)、设置表单默认值

contactForm: FormGroup = new FormGroup({
  name: new FormControl("默认值"),
  phone: new FormControl(15888888888)
})
登录后复制

6)、表单分组

contactForm: FormGroup = new FormGroup({
  fullName: new FormGroup({
    firstName: new FormControl(),
    lastName: new FormControl()
  }),
  phone: new FormControl()
})
登录后复制
<form [formGroup]="contactForm" (submit)="onSubmit()">
  <div formGroupName="fullName">
    <input type="text" formControlName="firstName" />
    <input type="text" formControlName="lastName" />
  </div>
  <input type="text" formControlName="phone" />
  <button>提交</button>
</form>
登录后复制
onSubmit() {
  console.log(this.contactForm.value.name.username)
  console.log(this.contactForm.get(["name", "username"])?.value)
}
登录后复制

2.3 FormArray

需求:在页面中默认显示一组联系方式,通过点击按钮可以添加更多联系方式组。

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 {
  // 表单
  contactForm: FormGroup = new FormGroup({
    contacts: new FormArray([])
  })

  get contacts() {
    return this.contactForm.get("contacts") as FormArray
  }

  // 添加联系方式
  addContact() {
    // 联系方式
    const myContact: FormGroup = new FormGroup({
      name: new FormControl(),
      address: new FormControl(),
      phone: new FormControl()
    })
    // 向联系方式数组中添加联系方式
    this.contacts.push(myContact)
  }

  // 删除联系方式
  removeContact(i: number) {
    this.contacts.removeAt(i)
  }

  ngOnInit() {
    // 添加默认的联系方式
    this.addContact()
  }

  onSubmit() {
    console.log(this.contactForm.value)
  }
}
登录后复制
<form [formGroup]="contactForm" (submit)="onSubmit()">
  <div formArrayName="contacts">
    <div
      *ngFor="let contact of contacts.controls; let i = index"
      [formGroupName]="i"
    >
      <input type="text" formControlName="name" />
      <input type="text" formControlName="address" />
      <input type="text" formControlName="phone" />
      <button (click)="removeContact(i)">删除联系方式</button>
    </div>
  </div>
  <button (click)="addContact()">添加联系方式</button>
  <button>提交</button>
</form>
登录后复制

2.4 内置表单验证器

1)、使用内置验证器提供的验证规则验证表单字段

import { FormControl, FormGroup, Validators } from "@angular/forms"

contactForm: FormGroup = new FormGroup({
  name: new FormControl("默认值", [
    Validators.required,
    Validators.minLength(2)
  ])
})
登录后复制

2)、获取整体表单是否验证通过

onSubmit() {
  console.log(this.contactForm.valid)
}
登录后复制
<!-- 表单整体未验证通过时禁用表单按钮 -->
<button [disabled]="contactForm.invalid">提交</button>
登录后复制

3)、在组件模板中显示为验证通过时的错误信息

get name() {
  return this.contactForm.get("name")!
}
登录后复制
<form [formGroup]="contactForm" (submit)="onSubmit()">
  <input type="text" formControlName="name" />
  <div *ngIf="name.touched && name.invalid && name.errors">
    <div *ngIf="name.errors.required">请填写姓名</div>
    <div *ngIf="name.errors.maxlength">
      姓名长度不能大于
      {{ name.errors.maxlength.requiredLength }} 实际填写长度为
      {{ name.errors.maxlength.actualLength }}
    </div>
  </div>
</form>
登录后复制

2.5 自定义同步表单验证器

  • 自定义验证器的类型是 TypeScript 类

  • 类中包含具体的验证方法,验证方法必须为静态方法

  • 验证方法有一个参数 control,类型为 AbstractControl。其实就是 FormControl 类的实例对象的类型

  • 如果验证成功,返回 null

  • 如果验证失败,返回对象,对象中的属性即为验证标识,值为 true,标识该项验证失败

  • 验证方法的返回值为 ValidationErrors | null

import { AbstractControl, ValidationErrors } from "@angular/forms"

export class NameValidators {
  // 字段值中不能包含空格
  static cannotContainSpace(control: AbstractControl): ValidationErrors | null {
    // 验证未通过
    if (/\s/.test(control.value)) return { cannotContainSpace: true }
    // 验证通过
    return null
  }
}
登录后复制
import { NameValidators } from "./Name.validators"

contactForm: FormGroup = new FormGroup({
  name: new FormControl("", [
    Validators.required,
    NameValidators.cannotContainSpace
  ])
})
登录后复制
<div *ngIf="name.touched && name.invalid && name.errors">
	<div *ngIf="name.errors.cannotContainSpace">姓名中不能包含空格</div>
</div>
登录后复制

2.6 自定义异步表单验证器

import { AbstractControl, ValidationErrors } from "@angular/forms"
import { Observable } from "rxjs"

export class NameValidators {
  static shouldBeUnique(control: AbstractControl): Promise<ValidationErrors | null> {
    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
    )
  })
登录后复制
<div *ngIf="name.touched && name.invalid && name.errors">
  <div *ngIf="name.errors.shouldBeUnique">用户名重复</div>
</div>
<div *ngIf="name.pending">正在检测姓名是否重复</div>
登录后复制

2.7 FormBuilder

创建表单的快捷方式。

  • this.fb.control:表单项

  • this.fb.group:表单组,表单至少是一个 FormGroup

  • this.fb.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: ["", [Validators.required]],
        lastName: [""]
      }),
      phone: []
    })
  }
}
登录后复制

2.8 监听表单值的变化

实际工作中,我们常常需要根据某个表单值得变化而进行相应的处理,一般可以使用ngModalChange或者表单来实现

2.8.1 ngModalChange

<div>
  <input type="text" [(ngModal)]="name" (ngModalChange)="nameChange()" />
</div>
登录后复制
import { FormControl, FormGroup } from "@angular/forms"

export class AppComponent {
  public name = &#39;a&#39;;
  public nameChange() {
  }
}
登录后复制

angular官方并不建议使用ngModalChange。

2.8.2 表单控制

<div [formGroup]="contactForm">
  <input type="text" formControlName="name" />
</div>
登录后复制
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 练习

1)、获取一组复选框中选中的值

<form [formGroup]="form" (submit)="onSubmit()">
  <label *ngFor="let item of Data">
    <input type="checkbox" [value]="item.value" (change)="onChange($event)" />
    {{ item.name }}
  </label>
  <button>提交</button>
</form>
登录后复制
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<Data> = [
    { 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)、获取单选框中选中的值

export class AppComponent {
  form: FormGroup

  constructor(public fb: FormBuilder) {
    this.form = this.fb.group({ gender: "" })
  }

  onSubmit() {
    console.log(this.form.value)
  }
}
登录后复制
<form [formGroup]="form" (submit)="onSubmit()">
  <input type="radio" value="male" formControlName="gender" /> Male
  <input type="radio" value="female" formControlName="gender" /> Female
  <button type="submit">Submit</button>
</form>
登录后复制

2.10 其他

  • patchValue:设置表单控件的值(可以设置全部,也可以设置其中某一个,其他不受影响)

  • setValue:设置表单控件的值 (设置全部,不能排除任何一个)

  • valueChanges:当表单控件的值发生变化时被触发的事件

  • reset:表单内容置空

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

以上是angular学习之聊聊两种类型的表单的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

如何在Ubuntu 24.04上安装Angular 如何在Ubuntu 24.04上安装Angular Mar 23, 2024 pm 12:20 PM

Angular.js是一种可自由访问的JavaScript平台,用于创建动态应用程序。它允许您通过扩展HTML的语法作为模板语言,以快速、清晰地表示应用程序的各个方面。Angular.js提供了一系列工具,可帮助您编写、更新和测试代码。此外,它还提供了许多功能,如路由和表单管理。本指南将讨论在Ubuntu24上安装Angular的方法。首先,您需要安装Node.js。Node.js是一个基于ChromeV8引擎的JavaScript运行环境,可让您在服务器端运行JavaScript代码。要在Ub

Angular学习之聊聊独立组件(Standalone Component) Angular学习之聊聊独立组件(Standalone Component) Dec 19, 2022 pm 07:24 PM

本篇文章带大家继续angular的学习,简单了解一下Angular中的独立组件(Standalone Component),希望对大家有所帮助!

angular学习之详解状态管理器NgRx angular学习之详解状态管理器NgRx May 25, 2022 am 11:01 AM

本篇文章带大家深入了解一下angular的状态管理器NgRx,介绍一下NgRx的使用方法,希望对大家有所帮助!

如何使用PHP和Angular进行前端开发 如何使用PHP和Angular进行前端开发 May 11, 2023 pm 04:04 PM

随着互联网的飞速发展,前端开发技术也在不断改进和迭代。PHP和Angular是两种广泛应用于前端开发的技术。PHP是一种服务器端脚本语言,可以处理表单、生成动态页面和管理访问权限等任务。而Angular是一种JavaScript的框架,可以用于开发单页面应用和构建组件化的Web应用程序。本篇文章将介绍如何使用PHP和Angular进行前端开发,以及如何将它们

一文探究Angular中的服务端渲染(SSR) 一文探究Angular中的服务端渲染(SSR) Dec 27, 2022 pm 07:24 PM

你知道 Angular Universal 吗?可以帮助网站提供更好的 SEO 支持哦!

Angular + NG-ZORRO快速开发一个后台系统 Angular + NG-ZORRO快速开发一个后台系统 Apr 21, 2022 am 10:45 AM

本篇文章给大家分享一个Angular实战,了解一下angualr 结合 ng-zorro 如何快速开发一个后台系统,希望对大家有所帮助!

浅析angular中怎么使用monaco-editor 浅析angular中怎么使用monaco-editor Oct 17, 2022 pm 08:04 PM

angular中怎么使用monaco-editor?下面本篇文章记录下最近的一次业务中用到的 monaco-editor 在 angular 中的使用,希望对大家有所帮助!

浅析Angular中的独立组件,看看怎么使用 浅析Angular中的独立组件,看看怎么使用 Jun 23, 2022 pm 03:49 PM

本篇文章带大家了解一下Angular中的独立组件,看看怎么在Angular中创建一个独立组件,怎么在独立组件中导入已有的模块,希望对大家有所帮助!

See all articles