我有以下模块:
// 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';
如何解决这个问题?
答案 0 :(得分:2)
模板绑定的范围是compoennt实例,您只能 使用组件实例提供的内容。
如果你添加
class MyComponent {
myIsNullOrUndefined = isNullOrUndefined;
然后你可以使用
<span *ngIf="!myIsNullOrUndefined(value)">Should not be there</span>
答案 1 :(得分:0)
稍微好一点
class MyComponent {
get isNullOrUndefined() {
return isNullOrUndefined;
}
还可以用于使任何导入的东西可见,例如Enum类型。