javascript - 将通用 JS 函数导入 Angular 模块

标签 javascript angular typescript

这里是 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 to window or document. They can't call console.log or Math.max. They are restricted to referencing members of the expression context.

关于javascript - 将通用 JS 函数导入 Angular 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52712459/

相关文章:

javascript - jsPDF:打印直接创建的 pdf 到打印机设备

angular - 如何使异步数据以 Angular 动态形式模式工作

Angular 2自定义管道在对象保存之前不更新

javascript - 从 React 中其他生成的路由链接到生成的路由

javascript - 在 for 循环中等待点击事件 - 类似于prompt()

javascript - 如何在 Owl Carousel (2) for angular 2/7 中实现 onChange 事件/回调/自定义点

typescript - TypeScript 中的奇怪对象可能是 "null"错误

javascript - 大于或等于(基于 bool 条件)

javascript - 将图像 blob 对象保存到本地文件系统 Javascript

angular - 当另一个变量更改时更新 Angular 组件中的变量