在Angular 9中失去上下文的ngFor内调用函数

问题描述 投票:0回答:1

我已将Angular项目从8.3更新为angular 9,但现在我在ngFor中调用的函数中失去了上下文。我使用apply设置上下文:

<div *ngFor="let item of myMenu;">
  <button (click)="item.function.apply(this, [item])">{{item.label}}</button>
</div>

我以这种方式设置数组:

this.myMenu.push({
  id: '1',
  label: 'ONE',
  function: this.one
});
this.myMenu.push({
  id: '2',
  label: 'TWO',
  function: this.two
});

这些是我要调用的功能:

  myThisOne: 'One';
  myThisTwo: 'Two';

  one(item) {
    console.log('id: ' + item.id + ', myThisOne: ' + this.myThisOne);
  }

  two(item) {
    console.log('id: ' + item.id + ', myThisTwo: ' + this.myThisTwo);
  }

但是我得到undefined。我无法在控制台的AppComponent中读取变量:

id: 1, myThisOne: undefined
id: 2, myThisTwo: undefined

[Angular 9中有什么变化?如何在我的功能中使用此功能?您可以在stackblitz上尝试。

angular this apply ngfor angular9
1个回答
0
投票

apply方法一切正常,以下代码中有问题:

© www.soinside.com 2019 - 2024. All rights reserved.