我創建表單,該表單的欄位之一是 cantrolValueAcessor-component。該欄位只是一個數字和幾個按鈕。點擊左鍵后數字減少,點擊右鍵后數字增加。
我想對 cantrolValueAcessor-field 使用驗證。當數字小于“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],
});
uj5u.com熱心網友回復:
由于您已經在使用表單控制元件,您可以輕松地添加它們minValue驗證器,然后在表單控制元件物件中檢查該錯誤。
https://angular.io/api/forms/Validators#min
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/443899.html
