2017-08-29 79 views
1

我有以下模块:角:在HTML另一个模块的使用功能/模板

// 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'; 

这怎么解决?

回答

1

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

如果添加

class MyComponent { 
    myIsNullOrUndefined = isNullOrUndefined; 

那么你可以使用

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

好吧,作品!然而,这不是一个很好的解决方案,不是吗(批评Angular不是你).. – SilverJan

+1

AFAIK有讨论使这种体验更好,但我不知道状态。 –