在 Angular 2 中绑定一个函数

Bind a function in Angular2+

我正在使用 AgGrid 并希望使用本地化。

我在 <ag-grid-angular HERE></ag-grid-angular>

中添加 [localeTextFunc]="localeTextFunc"

在我的 ts 文件中我有:

localeTextFunc(key, defaultValue) {
  console.log("key : ", key);
  console.log("defaultValue : ", defaultValue);
  console.log("this :", this);

  // need to use my translate service
  this.translate....
}

我的问题是 this 未定义。 如何将 this 绑定到我的函数?

一种解决方案是使用箭头函数。常规函数始终使用调用它的对象的范围(window、文档、按钮等)。

箭头函数总是使用它被定义为作用域的对象。

因此,在您的 .ts 文件中,如果您按如下方式创建函数,它应该可以工作:

localeTextFunc=(key, defaultValue)=>{
  console.log("key : ", key);
  console.log("defaultValue : ", defaultValue);
  console.log("this :", this);

  // need to use my translate service
  this.translate....
}

另一个解决方案是做这样的事情: <ag-grid-angular [localeTextFunc]="localeTextFunc.bind(this)"></ag-grid-angular>

不过,我会推荐第一个选项。