我有以下模块:
// 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/