Search code examples
htmlangulartypescriptcomponents

Using an imported Typescript function in Angular HTML


I have a TypeScript utility class myUtils.ts as below:

export class MyUtils {
  static doSomething(input: string) {
    // do something
  }
} 

I want to call this method in my component's HTML. In order to do that I imported this class in my component

import { MyUtils } from './utils'

and using in the component's HTML like so:

<ng-template #dynamicTableCell let-entry>  
  {{ MyUtils.doSomething(entry) }}
</ng-template>

The HTML is complaining with Unresolved variable or type MyUtils. Interestingly enough, I am able to do the same MyUtils.doSomething(someEntry) without any error in the component's component.ts file. It is just the HTML where it is complaining.

Can someone please tell me how to fix this problem in the HTML? Thanks in advance.


Solution

  • You can't use it, since template expressions are restricted to referencing members of the componence instance, you need to create the method in your component, or use Angular pipe in your case.

    component.ts

    import { MyUtils } from './utils';
    ...
    
    doSomething(entry) {
      MyUtils.doSomething(entry);
    }
    
    
    
    // or
    
    doSomething = MyUtils.doSomething;
    

    You can have a look at Template expressions doc.