使用内置验证器提供的验证规则验证表单字段
import { FormControl, FormGroup, Validators } from "@angular/forms"contactForm: FormGroup = new FormGroup({ name: new FormControl("默认值", [ Validators.required, Validators.minLength(2) ])})
获取整体表单是否验证通过
onSubmit() { console.log(this.contactForm.valid)}
<form [formGroup]="contactForm" (submit)="onSubmit()"> <input type="text" formControlName="name" /> <button [disabled]="contactForm.invalid">提交</button></form>
在组件模板中显示为验证通过时的错误信息
// 获取到 contactForm 下的 FormControl 实例化对象 nameget 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> <button [disabled]="contactForm.invalid">提交</button></form>