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

Sil*_*Jan 3 javascript angular2-template angular

我有以下模块:

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

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

// 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;
}
Run Code Online (Sandbox Code Playgroud)

但是,加载组件时我收到以下错误消息:

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)
Run Code Online (Sandbox Code Playgroud)

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

import {isNullOrUndefined} from '../util/util';
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题?

Gün*_*uer 8

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

如果添加

class MyComponent {
  myIsNullOrUndefined = isNullOrUndefined;  
Run Code Online (Sandbox Code Playgroud)

然后你可以使用

 <span *ngIf="!myIsNullOrUndefined(value)">Should not be there</span>
Run Code Online (Sandbox Code Playgroud)

  • AFAIK 有讨论以改善这种体验,但我不知道状态。 (3认同)
  • 好吧,工作了!然而,这并不是一个很好的解决方案不是吗(批评 Angular 不是你).. (2认同)