Vin*_*oft 4 formbuilder angularjs angular
我正在使用Angular2的FormBuilder开发一个带有自定义验证的表单.问题:在customValidator中我this用来访问本地对象data.我在undefined执行验证时遇到错误.
看起来customValidator在不同的对象中执行,因此更改this引用
问题:如何将引用传递this给customValidator?
export class Ast {
public data:any;
public myForm:FormGroup;
constructor(private _fb:FormBuilder) {
this.data = {foo: "bar"};
}
customValidator(c: FormControl) {
if (this.data.foo == "bar") { // This line crashes
// DO something
}
}
ngOnInit() {
this.myForm = this._fb.group({
some_field: ['', [<any>Validators.required], this.customValidator]
})
}
}
Run Code Online (Sandbox Code Playgroud)
使用箭头函数,以确保函数绑定到此:
some_field: ['', [<any>Validators.required], c => this.customValidator(c)]
Run Code Online (Sandbox Code Playgroud)
由于打字问题(我认为,铸造AbstractControl到a)FormControl,接受的答案在Angular 2.0中对我不起作用.但是,以下内容很好地解决了这个问题:
ngOnInit() {
this.myForm = this._fb.group({
some_field: ['', [<any>Validators.required], this.customValidator.bind(this)]
});
}
Run Code Online (Sandbox Code Playgroud)
使用.bind(this)对验证器的引用为我做了诀窍.
| 归档时间: |
|
| 查看次数: |
1136 次 |
| 最近记录: |