在 Angular HTML 中使用导入的 Typescript 函数
Using an imported Typescript function in Angular HTML
我有一个 TypeScript 实用程序 class myUtils.ts
如下:
export class MyUtils {
static doSomething(input: string) {
// do something
}
}
我想在我的组件 HTML 中调用这个方法。为此,我在组件
中导入了这个 class
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 管道。
component.ts
import { MyUtils } from './utils';
...
doSomething(entry) {
MyUtils.doSomething(entry);
}
// or
doSomething = MyUtils.doSomething;
您可以查看 Template expressions 文档。
我有一个 TypeScript 实用程序 class myUtils.ts
如下:
export class MyUtils {
static doSomething(input: string) {
// do something
}
}
我想在我的组件 HTML 中调用这个方法。为此,我在组件
中导入了这个 classimport { 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 管道。
component.ts
import { MyUtils } from './utils';
...
doSomething(entry) {
MyUtils.doSomething(entry);
}
// or
doSomething = MyUtils.doSomething;
您可以查看 Template expressions 文档。