这里是stackblits stackBlits实例的链接,我创建了数组并在数组的对象中传递了方法引用,但是构造函数注入的属性没有定义。
import { HttpClient } from '@angular/common/http';
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
constructor(public http: HttpClient) {
alert(http);
}
PrintTwo() {
alert(this.http);
alert('two');
}
btns: Array<any> = [
{
name: 'two',
title: 'two',
functionToCall: this.PrintTwo,
class: 'btn-danger',
},
];
}这是HTML部件
<ng-container *ngFor="let btn of btns">
<button
class="btn me-4 {{ btn.class }}"
[title]="btn.title"
#btnElement
(click)="btn.functionToCall()">
{{ btn.name }}
</button>
</ng-container>这里是从警告对象中的构造函数来的,但是当从方法调用时,它是以未定义的方式出现的。
我不知道为什么会这样,我认为当我传递方法时,整个完整的方法被传递了,没有其他属性,这意味着它不以类方法作为参考,它所做的一切都是直接在方法中获取方法代码。
发布于 2022-08-18 09:45:43
表达式btn.functionToCall()是在btn上下文中调用的。这意味着this指向:
{
name: 'two',
title: 'two',
functionToCall: this.PrintTwo,
class: 'btn-danger',
}尝试将PrintTwo绑定到正确的上下文:
{
name: 'two',
title: 'two',
functionToCall: this.PrintTwo.bind(this),
class: 'btn-danger',
}https://stackoverflow.com/questions/73400727
复制相似问题