nothingisnecessary
nothingisnecessary

Reputation: 6243

Angular How to invoke pipe from string with name of pipe?

In Angular 2 how can I use reflection (or whatever I would call it, here) to use a pipe? I have a string with the name of the pipe (like "lowercase") and I want to invoke the pipe using only that string.

For example:

JSON

var cols = [{ dataProperty: "city", pipeName: "lowercase"},{ dataProperty: "state", pipeName: "uppercase"}]
var rows = [{city: 'Walla Walla', state: 'wa'}];

HTML (Angular component excerpt)

{{ rowData[col.dataProperty] | this.[col.pipeName] }}

But this code didn't work.

What do I use instead of this.[col.pipeName] to give me the equivalent of dynamically calling uppercase or lowercase (or whatever pipe I define in pipeName, assuming it is a pipe my code can access)?

Upvotes: 6

Views: 4543

Answers (1)

seabass
seabass

Reputation: 1120

If your json data is going to be hardcoded

var cols = [{dataProperty: "city",  pipe: new LowerCasePipe()},
            {dataProperty: "state", pipe: new UpperCasePipe()}]

Then in your template html

{{col.pipe.transform(rowData[col.dataProperty])}}

all default angular pipes implement the PipeTransform interface, which has the transform method on it.


If your data will come from an api

You could leave it as pipeName: "uppercase" and pull the corresponding pipe out of a dictionary.

export class PipeManager {
  private static _pipes = {
    'upperCase': new UpperCasePipe(),
    'lowerCase': new LowerCasePipe(),
    'currency': new CurrencyPipe('en')
  };

  public static PipeForKey(key: string) {
    return PipeManager._pipes[key];
  }
}

Then in your template html

{{PipeManager.PipeForKey(col.pipeName).transform(rowData[col.dataProperty])}}

This solution could be cleaned up a bit but, hopefully you get the idea.

Upvotes: 8

Related Questions