Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create a global function that could be used in angular 4 template

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?

like image 863
PaladiN Avatar asked Dec 03 '22 21:12

PaladiN


1 Answers

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.

like image 87
Armen Vardanyan Avatar answered Dec 29 '22 09:12

Armen Vardanyan