我创建表单,该表单的一个字段是cantrolValueAcessor组件。此字段只是一个数字和几个按钮。点击左侧按钮后数量减少,点击右侧按钮后数量增加。
我想对cantrolValueAcessor字段使用验证。当数字小于"0"时,必须显示错误消息。
这是我的尝试。
CVA代码:
import { Component, forwardRef } from '@angular/core';
import {
ControlValueAccessor,
NG_VALIDATORS,
NG_VALUE_ACCESSOR,
Validator,
} from '@angular/forms';
@Component({
selector: 'hello',
template: `
<button (click)="minus()">minus</button>
<button (click)="plus()">plus</button>
{{ value }}
`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => HelloComponent),
multi: true,
},
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => HelloComponent),
multi: true,
},
],
})
export class HelloComponent implements ControlValueAccessor, Validator {
value: number;
validate() {
return this.value > 0 ? null : { positive: true };
}
onChange: any = () => {};
onTouch: any = () => {};
registerOnChange(fn: any) {
this.onChange = fn;
}
registerOnTouched(fn: any) {
this.onTouch = fn;
}
writeValue(input: number) {
this.value = input;
}
minus() {
this.value -= 1;
}
plus() {
this.value += 1;
}
}
父代码:
this.form = this.fb.group({
name: [null, [Validators.required]],
email: [null, [Validators.required, Validators.email]],
buttons: [0],
});
由于您已经在使用表单控件,您可以很容易地添加它们minValue
验证器,然后在表单控件对象中检查该错误。
https://angular.io/api/forms/Validators#min