面试题答案
一键面试- 在组件类中定义表单控件并添加验证器:
import { Component } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app - email - form', templateUrl: './email - form.component.html', styleUrls: ['./email - form.component.css'] }) export class EmailFormComponent { emailControl = new FormControl('', [Validators.required, Validators.email]); getEmailErrorMessage() { if (this.emailControl.hasError('required')) { return '你必须输入一个值'; } return this.emailControl.hasError('email')? '输入的邮箱格式不正确' : ''; } }
- 在模板中使用该表单控件:
<form> <input type="email" [formControl]="emailControl"> <div *ngIf="emailControl.hasError('required') && (emailControl.touched || emailControl.dirty)"> {{getEmailErrorMessage()}} </div> <div *ngIf="emailControl.hasError('email') && (emailControl.touched || emailControl.dirty)"> {{getEmailErrorMessage()}} </div> </form>
在上述代码中:
- 在组件类中,使用
FormControl
创建了emailControl
表单控件,并通过Validators.required
和Validators.email
添加了必填和邮箱格式验证。 getEmailErrorMessage
方法用于根据验证结果返回相应的错误信息。- 在模板中,通过
[formControl]
绑定表单控件,并使用*ngIf
指令根据验证状态显示错误信息。只有当控件被触摸(touched
)或值发生变化(dirty
)时,才显示错误信息。