Reputation: 1180
Bit of an Angular/Typescript newb here.
I've set up a JavaScript library of exported, helper functions that I know want to import into an Angular components, and use in those components' .html template files.
Here's my Javascript library, template-functions/data-types.ts:
export const isNumeric = val => !Array.isArray(val) && (val - parseFloat(val) + 1) >= 0;
It's a simple arrow function that I'm exporting:
Here's how I'm importing it in my component:
import { Component, OnInit, Input } from '@angular/core';
import { MyModel } from '../model/my-model';
import { isNumeric } from '../template-functions/data-types';
@Component({
selector: 'my-module',
templateUrl: './my-module.html'
})
export class MyModule implements OnInit {
@Input() public mymodeldetails: MyModel;
constructor() { }
ngOnInit() { }
// isNumeric = val => !Array.isArray(val) && (val - parseFloat(val) + 1) >= 0;
}
This is after several hours of having the Angular compiler and VSCode telling me that it couldn't find the data-types module, even though the path was correct. I had a .js file extensions instead of a .ts one!
So now Angular can see my isNumeric function, but I'm the .html template file does not see it with what I've done so far. The browser throws the error "_co.isNumeric is not a function".
What more do I need to do to get my Angular template to see my imported function?
I'm using Angular 6.
Upvotes: 5
Views: 1712
Reputation: 1
For future readers:
To use an imported function in the template, assign it to a property.
import { isNumeric } from '../template-functions/data-types';
export class MyComponent implements OnInit {
isNumeric = isNumeric;
}
Upvotes: 0
Reputation: 73721
To make it visible in the template, wrap it in a component method:
import { isNumeric } from '../template-functions/data-types';
export class MyComponent implements OnInit {
isNumeric(val: any): boolean {
return isNumeric(val);
}
}
See this stackblitz for a demo.
As explained in the Angular template syntax documentation:
The expression context is typically the component instance. (...) Template expressions cannot refer to anything in the global namespace (except
undefined
). They can't refer towindow
ordocument
. They can't callconsole.log
orMath.max
. They are restricted to referencing members of the expression context.
Upvotes: 5