我的验证程序应确保用户不要尝试输入小于1或大于20的值,但是如果我输入21或-1,验证程序就不会出现。
这是我的组件类中的内容:
export function invalidCount(value: number): ValidatorFn {
if(value > 0 && value <= 20) {
return null;
} else {
return (control: AbstractControl): {[key: string]: any} => {
console.log("error");
return {'badValue': value};
};
}
}
export class Foo implements OnInit {
//other important code related to @Component...
count: number = 1;
control = new FormControl(this.count, invalidCount(this.count));
}
然后在我拥有的模板中
<mat-form-field>
<mat-label>Choose a value</mat-label>
<input matInput type="number" [(ngModel)]="count" required min="1"
max="20"
[formControl]="control">
</mat-form-field>
答案 0 :(得分:0)
如下更新您的验证器功能:
count: number = 1;
control = new FormControl(this.count, this.invalidCount)
invalidCount(control: AbstractControl) {
if(control.value > 0 && control.value <= 20) {
return null;
} else{
return {'badValue': control.value};
};
}
我已经创建了stackblitz演示:https://stackblitz.com/edit/angular-prrdva