[英]Angular - Template driven forms - custom validator function in the controller
[英]Angular - Custom validator function in the controller: How to access 'this'?
我正在尝试为Angular中的表单实现自定义验证器。 如果可以访问控制器的this
,那将是完美的,但是在validator函数中未定义。
这是我的验证器功能:
validateSuccessShortName(control: AbstractControl) {
//can't read this.randomProp, because this is undefined
if (control.value.length > this.randomProp.length) {
return {value: control.value};
}
return null;
}
这是一个STACKBLITZ演示此问题。
我是在做错什么,还是在Angular框架中这根本不可能?
https://stackblitz.com/edit/ionic-tqp9o1?embed=1&file=pages/home/home.ts
为了将来的改进,最好将所有验证移到另一个文件中,并且每个功能的第一个参数都必须配置。 您的验证程序不得仅依赖于config对象依赖this
只需更改this.validateSuccessShortName.bind(this)
,因为您缺少上下文
shortName: new FormControl('', [
this.validateSuccessShortName.bind(this)
])
您的角度验证器未引用您的组件属性。 为了解决这个问题,你需要绑定this
来验证。
export class HomePage {
private arr: Array<any>;
private thevalue: string;
public thisForm: FormGroup;
public randomProp: string;
constructor(
private modal: ModalController,
public navCtrl: NavController) {
this.thevalue = "Initial value";
this.randomProp = "This is a random property";
this.thisForm = new FormGroup({
shortName: new FormControl('', [
this.validateSuccessShortName.bind(this)
])
});
}
validateSuccessShortName(control: AbstractControl) {
if (control.value.length > this.randomProp.length) {
return {value: control.value};
}
return null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.