面试题答案
一键面试实现步骤
- 创建一个自定义验证器函数,该函数接收一个
AbstractControl
参数。 - 在函数内部,获取输入字符串的长度,判断其是否在5到10之间。
- 如果长度不符合要求,返回一个包含错误信息的对象;如果符合要求,返回
null
。 - 在模板驱动表单中使用该自定义验证器。
代码示例
- 自定义验证器函数
import { AbstractControl, ValidationErrors } from '@angular/forms';
export function stringLengthValidator(control: AbstractControl): ValidationErrors | null {
const value = control.value;
if (typeof value ==='string' && (value.length < 5 || value.length > 10)) {
return { stringLength: true };
}
return null;
}
- 在模板驱动表单中使用
<form #myForm="ngForm">
<input type="text" name="inputText" [(ngModel)]="inputValue" [ngModelOptions]="{standalone: true}" [validators]="[stringLengthValidator]" />
<div *ngIf="myForm.controls['inputText']?.hasError('stringLength')">
字符串长度必须在5到10之间
</div>
<button type="submit">提交</button>
</form>
在组件类中引入验证器:
import { Component } from '@angular/core';
import { stringLengthValidator } from './string-length-validator';
@Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html'
})
export class MyFormComponent {
inputValue = '';
}