【问题标题】:Angular 5 template can't call static methodAngular 5模板不能调用静态方法
【发布时间】:2018-08-19 01:25:34
【问题描述】:

在我的组件中,我定义了一个简单的静态方法:

export class AppComponent implements OnInit {
    static onSelectAllPressed(element: AudioElement): void {
    }

然后在我的模板 html 文件中,我尝试将其链接到按钮单击:

<button mat-button (click)="AppComponent.onSelectAllPressed(element)">Select All</button>

它可以毫无问题地构建 (ng build --prod),但是当我单击按钮时,我在控制台中收到错误消息:

错误类型错误:无法读取未定义的属性“onSelectAllPressed”

我不明白为什么这会失败。难道我们根本就不允许访问静态方法吗?

【问题讨论】:

  • 这将转换为AppComponent.AppComponent.onSelectAllPressed(element)。试试(click)="onSelectAllPressed(element)"
  • 这导致ERROR TypeError: t.component.onSelectAllPressed is not a function
  • 查看这个答案。您不能从视图中调用静态方法,您需要通过组件公开该方法。 stackoverflow.com/a/41857120/1411687
  • 奇怪的是它们不支持静态函数。那我就让它保持非静态。谢谢。

标签: static-methods angular5


【解决方案1】:

这里不需要静态方法,可以使用匿名函数

onSelectAllPressed = (element: AudioElement) => element.whatYouNeed;

而且很容易在模板中调用

<button mat-button
    (click)="onSelectAllPressed(element)">
Select All</button>

【讨论】:

  • 最好像@alex wiese 所说的那样做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-22
  • 1970-01-01
  • 2011-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多