为什么异步验证器回调不具有组件上下文?

时间:2016-12-25 19:38:21

标签: angular typescript

我注意到我无法从其中一个方法访问该组件,我将其分配给异步验证器(使用超时模拟)。

所以我需要使用bind()来强制它的上下文。使用异步验证器总是这样吗?或者还有什么遗漏,以便这个方法保持它所属的上下文?

以下是代码:

https://embed.plnkr.co/xJz7Z66SUUFaN8QCYcrJ/

请注意验证者的分配:

this.asyncExampleValidator.bind(this)

在data-driven.component.ts

1 个答案:

答案 0 :(得分:2)

你可以Use Instance Functions 保持“这个”你想要的地方

这里

 onAddHobby() {
      (<FormArray>this.myForm.get('hobbies')).push(new FormControl('', Validators.required, this.asyncExampleValidator.bind(this)));
    }

onAddHobby“这个”可能不是你所期望的 和asyncExampleValidator遭受相同的

'this' in TypeScript