【问题标题】:Using an imported Typescript function in Angular HTML在 Angular HTML 中使用导入的 Typescript 函数
【发布时间】:2021-10-10 02:24:07
【问题描述】:

我有一个 TypeScript 实用程序类 myUtils.ts,如下所示:

export class MyUtils {
  static doSomething(input: string) {
    // do something
  }
} 

我想在我的组件的 HTML 中调用这个方法。为了做到这一点,我在我的组件中导入了这个类

import { MyUtils } from './utils'

并像这样在组件的 HTML 中使用:

<ng-template #dynamicTableCell let-entry>  
  {{ MyUtils.doSomething(entry) }}
</ng-template>

HTML 向Unresolved variable or type MyUtils 抱怨。有趣的是,我可以在组件的component.ts 文件中执行相同的MyUtils.doSomething(someEntry) 而不会出现任何错误。它只是抱怨的 HTML。

谁能告诉我如何在 HTML 中解决这个问题?提前致谢。

【问题讨论】:

  • 您是否考虑过使用 Angular 服务而不是您的 utils 类。在您的组件的 html 中,您将能够 {{newService.doSomething(entry)}}
  • 你不能,但是在你的组件类doSomething = MyUtils.doSomething;中添加一个代理成员并使用它并不麻烦

标签: html angular typescript components


【解决方案1】:

你不能使用它,因为模板表达式仅限于引用组件实例的成员,你需要在你的组件中创建方法,或者在你的情况下使用 Angular 管道。

component.ts

import { MyUtils } from './utils';
...

doSomething(entry) {
  MyUtils.doSomething(entry);
}



// or

doSomething = MyUtils.doSomething;

你可以看看Template expressions doc。

【讨论】:

  • 谢谢,@coturiv!这真的很有帮助。
猜你喜欢
  • 2021-06-10
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-17
  • 2022-01-16
  • 2016-01-12
  • 1970-01-01
相关资源
最近更新 更多