Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 838
nothingisnecessary Avatar asked Mar 08 '18 20:03

nothingisnecessary


People also ask

How do you indicate pipe in Angular?

Marking a class as a pipelink To mark a class as a pipe and supply configuration metadata, apply the @Pipe decorator to the class. Use UpperCamelCase (the general convention for class names) for the pipe class name, and camelCase for the corresponding name string. Do not use hyphens in the name .

Can you name some built in Angular pipes?

The following are commonly used built-in pipes for data formatting: DatePipe : Formats a date value according to locale rules. UpperCasePipe : Transforms text to all upper case. LowerCasePipe : Transforms text to all lower case.

How are pipes executed in Angular?

You use data binding with a pipe to display values and respond to user actions. If the data is a primitive input value, such as String or Number , or an object reference as input, such as Date or Array , Angular executes the pipe whenever it detects a change for the input value or reference.


1 Answers

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.

like image 167
seabass Avatar answered Oct 26 '22 09:10

seabass