5

I have the following module:

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

I want to use the function in my component:

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

However, I am getting the following error message when the component is loaded:

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)

Importing the function like this doesn't help either:

import {isNullOrUndefined} from '../util/util';

How can this be solved?

2 Answers 2

13

The scope for template bindings is the compoennt instance and you can only use what the component instance provides.

If you add

class MyComponent {
  myIsNullOrUndefined = isNullOrUndefined;  

then you can use

 <span *ngIf="!myIsNullOrUndefined(value)">Should not be there</span>
Sign up to request clarification or add additional context in comments.

3 Comments

Alright, works! However, this is not really a nice solution isn't it (criticizing Angular not you)..
AFAIK there were discussions to make this experience better, but I don't know about the status.
It doesn't have to be a different name BTY, could do isNullOrUndefined = isNullOrUndefined; RHS is valued to be the reference.
0

Slightly nicer is

class MyComponent {
   get isNullOrUndefined() {
     return isNullOrUndefined;
   }

Also can be used to make any imported thing visible, eg Enum types.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.