2017-08-29 84 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有討論使這種體驗更好,但我不知道狀態。 –