通过对象的动态分配和调用,Angular 6?

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

我为动态生成的按钮分配了一个点击处理程序。我在点击处理程序函数内部调用了回调函数。不幸的是,我收到一条错误消息,指出“回调函数不是函数”。我在下面提供基本代码。

HTML(组件2)-

<button *ngFor="let btn of content.buttons" type="button" (click)="btn.func()" class="{{btn.type}}"><span class="btn-text">{{btn.text}}</span></button>

TS(组件2)-

@Component({
  selector: 'app-popup',
})

@Input() content;

我从中传递数据的组件代码-

HTML(组件1)-

<app-popup [content]="popupContent"></app-popup>

TS(组件1)-

this.popupContent = {
  "buttons":[{
        "text":"OK",
        "type":"btn-red",
        "func": this.someHandler
  }]
};

someCallbackFunction(){
  console.log('I am a callback function');
}

someHandler(){
  this.someCallbackFunction();
}

当我单击按钮时触发事件时,它将引发此错误-

ERROR TypeError: this.someCallbackFunction is not a function

我也尝试过设置处理程序,如

(click)="btn[func]()" 

但是不幸的是,这对我没有用。

请提出解决方案。谢谢:)

javascript html angularjs angular this
2个回答
0
投票

尝试通过粗箭头函数调用该函数,那样它应该具有正确的this上下文。只需更改定义方式即可。

"buttons":[{
     "text":"OK",
     "type":"btn-red",
     "func": () => { this.someHandler(); }
}];

0
投票

"func": this.someHandler修改为"func": this.someHandler

尝试这样:

Working Demo

buttons =[{
    "text":"OK",
    "type":"btn-red",
    "func" :() => this.someHandler()
}]
© www.soinside.com 2019 - 2024. All rights reserved.