Chi*_*uin 5 javascript typescript angular
这里是 Angular/Typescript 的新手。
我已经设置了一个导出的辅助函数 JavaScript 库,我知道这些函数想要导入到 Angular 组件中,并在这些组件的 .html 模板文件中使用。
这是我的 Javascript 库 template-functions/data-types.ts:
export const isNumeric = val => !Array.isArray(val) && (val - parseFloat(val) + 1) >= 0;
Run Code Online (Sandbox Code Playgroud)
这是我导出的一个简单的箭头函数:
以下是我将其导入组件的方法:
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;
}
Run Code Online (Sandbox Code Playgroud)
这是在 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);
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅此 stackblitz的演示。
正如 Angular 模板语法文档中所述:
表达式上下文通常是组件实例。(...) 模板表达式不能引用全局命名空间中的任何内容(除了
undefined)。他们不能引用windowordocument。他们不能打电话console.log或Math.max。它们仅限于引用表达式上下文的成员。
| 归档时间: |
|
| 查看次数: |
1531 次 |
| 最近记录: |