javascript - Angular:在 HTML/模板中使用另一个模块的功能

标签 javascript angular angular2-template

我有以下模块:

// in module app/util/utils.ts
export function isNullOrUndefined(obj: any) {
  return obj === undefined || obj === null || obj === 'undefined' || obj === '';
}

我想在我的组件中使用这个函数:

// in module app/component/component.ts
@Component({
  selector: 'app-component',
  template: `
    <span *ngIf="!isNullOrUndefined(value)">Should not be there</span>
`
})
export class Component {
 value = null;
}

但是,加载组件时出现以下错误消息:

Component.html:2 ERROR 
TypeError: _co.isNullOrUndefined is not a function
    at Object.View_Component_1._co [as updateDirectives] (Component.html:2)
    at Object.debugUpdateDirectives [as updateDirectives] (core.es5.js:13065)
    at checkAndUpdateView (core.es5.js:12245)
    at callViewAction (core.es5.js:12610)
    at execEmbeddedViewsAction (core.es5.js:12568)
    at checkAndUpdateView (core.es5.js:12246)
    at callViewAction (core.es5.js:12610)
    at execComponentViewsAction (core.es5.js:12542)
    at checkAndUpdateView (core.es5.js:12251)
    at callViewAction (core.es5.js:12610)

像这样导入函数也无济于事:

import {isNullOrUndefined} from '../util/util';

如何解决?

最佳答案

模板绑​​定的范围是组件实例,您只能使用组件实例提供的内容。

如果你添加

class MyComponent {
  myIsNullOrUndefined = isNullOrUndefined;  

然后你就可以使用了

 <span *ngIf="!myIsNullOrUndefined(value)">Should not be there</span>

关于javascript - Angular:在 HTML/模板中使用另一个模块的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45945084/

相关文章:

javascript - 相当于 jQuery 的原型(prototype)选择器

javascript - 如何从reactjs中的按钮将 Prop 传递给函数

javascript - 在 phonegap 中禁用方向更改动画

javascript - 更改页面的背景颜色

angular - 如何模拟包含 http 请求并返回 observable 的服务?

Angular 2 Forms - 在子组件级别分配 ngControl

javascript - 如何播放对话框流的输出音频(int 数组)

angular - 将 null 设置为输入字段的空字符串值

javascript - angular2/javascript - NgFor 循环遍历对象内部的数组

javascript - Angular2-在标题和侧边栏组件之间传递标志状态