Reputation: 101
In my application I'll need to create a functions library to be accessed from different components. What is the best way to do this? Do I need to make a service with all the functions or a class or a module or a component?
In this library if I call a function from a component and this function need to access a variable in the caller, will it be possible to do?
Upvotes: 1
Views: 1437
Reputation: 6131
If it's just a set of one off helper functions the easiest way is create an @Injectable service with your helper methods then inject that into any component that requires them. You can provide public vars as well so they're accessible in your html.
@Injectable()
export class Helpers {
helper1() { return "hello"; }
helper2(x) { return x + 1 }
}
@Component({
providers: [Helpers],
template: "<div>{{helper1()}}</div>" // will display 'hello'
)}
export class MyComponent {
public helper1: Function = Helpers.helper1;
constructor() {
console.log(Helpers.helper2(5)); // will output '6'
}
}
This works great for a simple set of random utility functions. If you need something more in depth please explain and we can provide alternate solutions.
Upvotes: 2