这里是 Angular/Typescript 的新手。
我已经建立了一个 JavaScript 库,包含导出的辅助函数,我知道这些函数要导入到 Angular 组件中,并在这些组件的 .html 模板文件中使用。
这是我的 Javascript 库,template-functions/data-types.ts:
export const isNumeric = val => !Array.isArray(val) && (val - parseFloat(val) + 1) >= 0;
我要导出的是一个简单的箭头函数:
这是我将它导入我的组件的方式:
import { Component, OnInit, Input } from '@angular/core';
import { MyModel } from '../model/my-model';
import { isNumeric } from '../template-functions/data-types';
@Component({
selector: 'my-module',
templateUrl: './my-module.html'
})
export class MyModule implements OnInit {
@Input() public mymodeldetails: MyModel;
constructor() { }
ngOnInit() { }
// isNumeric = val => !Array.isArray(val) && (val - parseFloat(val) + 1) >= 0;
}
这是在 Angular 编译器和 VSCode 告诉我它找不到数据类型模块的几个小时之后,即使路径是正确的。我的文件扩展名为 .js 而不是 .ts!
现在 Angular 可以看到我的 isNumeric 函数,但是 .html 模板文件没有看到我到目前为止所做的。浏览器抛出错误“_co.isNumeric 不是函数”。
我还需要做什么才能让我的 Angular 模板看到我导入的函数?
我正在使用 Angular 6。
最佳答案
要使其在模板中可见,请将其包装在组件方法中:
import { isNumeric } from '../template-functions/data-types';
export class MyComponent implements OnInit {
isNumeric(val: any): boolean {
return isNumeric(val);
}
}
参见 this stackblitz用于演示。
如 Angular 模板语法中所述 documentation :
The expression context is typically the component instance. (...) Template expressions cannot refer to anything in the global namespace (except
undefined
). They can't refer towindow
ordocument
. They can't callconsole.log
orMath.max
. They are restricted to referencing members of the expression context.
关于javascript - 将通用 JS 函数导入 Angular 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52712459/