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