可以通过使用模板驱动表单或响应式表单来限制用户只能填写一个字段。
在模板驱动表单中,您可以使用ngModel指令的属性进行验证。您可以在input标签中添加“[ngModelOptions]”并使用“{standalone: true}”来禁用默认的“ngModel”指令行为。添加自定义验证器函数并在它们返回false时将错误消息呈现给用户。
例如:
在组件中定义验证器函数:
import { Directive } from '@angular/core';
import { NG_VALIDATORS, FormControl, Validator } from '@angular/forms';
@Directive({
selector: '[onlyOne]',
providers: [{provide: NG_VALIDATORS, useExisting: OnlyOneValidatorDirective, multi: true}]
})
export class OnlyOneValidatorDirective implements Validator {
validate(control: FormControl): {[key: string]: any} | null {
const val = control.value !== undefined ? control.value : '';
const siblingControl = control.parent && control.parent.controls ? control.parent.controls.find((c: FormControl) => c !== control) : null;
const siblingVal = siblingControl && siblingControl.value !== undefined ? siblingControl.value : '';
if (val && siblingVal) {
return {'onlyOne': true};
}
return null;
}
}
请注意,我