在Angular HTML中使用导入的Typescript函数



我有一个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管道。

component.ts

import { MyUtils } from './utils';
...
doSomething(entry) {
MyUtils.doSomething(entry);
}

// or
doSomething = MyUtils.doSomething;

你可以看一下模板表达式文档。

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

MyUtils = MyUtils;

看起来很奇怪,但这是我的工作

最新更新