I want to create a reusable function that could be used in angular templates. I have created a function as:
export function stringSplit(string : string, separator : string = '/') : any {
return string.split(separator);
}
I have tried to add into the template like this:
<p> stringSplit('hello/user') </p>
But i am getting this error:
ERROR TypeError: _co.stringSplit is not a function
I am not sure how we can create and use global functions in angular.
Can we perform this operation in angular?
What is the best solution in this situation?
The answer is you should not. Dependency Injection is a powerful tool provided by Angular with the sole purpose of sharing functionality across components without maintaining a global scope. What you should really do is create a service, add a method to it, inject your service into any component that needs it, and invoke it there.
Judging by your question it would be nice to have a pipe to perform the operation you need. Pipes are used to manipulate data inside any template (making the function virtually global to all templates that belong to components that belong to modules which either declare or import the pipe). You can write this:
@Pipe({name: 'splitString'})
export class SplitString implements PipeTransform {
transform(value: string, separator: string): string[] {
return value.split(separator);
}
}
And in your html:
<p>{{ myString | splitString : ',' }} </p>
Read more about pipes here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With