Angular2 FormBuilder: Using 'this' in a custom validator

喜你入骨 提交于 2019-11-29 14:48:38

Using an arrow function, to make sure the function is bound to this:

some_field: ['', [<any>Validators.required], c => this.customValidator(c)]
Michael Oryl

The accepted answer didn't work for me in Angular 2.0 due to typing issues (casting an AbstractControl to a FormControl, I believe). The following, however, solved the problem quite nicely:

ngOnInit() {
    this.myForm = this._fb.group({
        some_field: ['', [<any>Validators.required], this.customValidator.bind(this)]
    });
}

Using the .bind(this) on the reference to the validator did the trick for me.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!