How can we utilize a pipe in Angular by referencing it with the pipe's name from a string

How can I implement dynamic pipe invocation in Angular 2 using reflection or a similar method? I have a string containing the name of the desired pipe (e.g. "lowercase") and I want to apply that pipe to a value using only the string.

For instance:

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] }}

However, this implementation did not yield the expected results.

Is there an alternative to using this.[col.pipeName] to dynamically invoke the appropriate pipe based on the provided pipe name, such as calling uppercase or lowercase, assuming the specified pipe is accessible in my code?

Answer №1

If you need to hardcode your json data

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

In your HTML template

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

All default angular pipes use the PipeTransform interface, with the transform method.


If your data is from an API

You can keep it as pipeName: "uppercase" and access the corresponding pipe from a dictionary.

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

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

In your HTML template

{{PipeManager.getPipe(col.pipeName).transform(rowData[col.propertyData])}}

This method could use some refining, but I hope you grasp the concept.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible that the installation issue with 'File' from ionic-native is due to dependencies?

As a newcomer to Ionic2, I'm facing some beginner obstacles. Despite my extensive search efforts, I haven't been able to find any examples related to my issue. My current goal is to write a file to a specific directory on the device using Ionic2 ...

An out of memory exception while running the ng build command in Docker results in a fatal

Currently, I am facing the challenge of developing the frontend for a web application within a Node.js Docker container on my Windows PC. Due to the limitations in available base Images, I opted for this specific one from DockerHub as it has a substantial ...

Is it possible for me to reinstall npm in an Angular project as a solution?

I recently started working on an Angular 9 project and installed various libraries. However, I encountered some issues with ngx-gallery and Renderer2 which led me to make edits in files like core.d.ts within the node_module/angular/core directory. As a new ...

Implementation of search filtering pipe function

Currently, I am implementing item filtering using a pipe in my Angular application. The search input field is located in the search.html file while the list of items is displayed in the List.html file. However, I've encountered an issue where change ...

"Exploring the World of Websockets Using Ionic 3 and Angular

How can I successfully implement a Websocket in Ionic 3 and Angular 4? I attempted to use the socket.io-client package, but when I try to connect the websocket using the following code: this.socket = io(this.urls.websocket, {transports: ['websocket& ...

Utilizing this.$refs in Vue TypeScript: Handling Vue and Element Errors with Vue[] and Element[]

When attempting to use this.$refs.calendars.$refs.calendar.showPageRange() in JavaScript, it works fine. However, when trying to implement it in TypeScript, an error occurs: '$refs' does not exist on type 'Vue | Element | Vue[] | Element[]&a ...

Utilizing npm/buffer package within a TypeScript module

I'm interested in implementing this NPM package: https://www.npmjs.com/package/buffer I'm unsure about how to convert this line of code into typescript: var Buffer = require('buffer/').Buffer Could you provide me with the correct code ...

OpenID Connect does not provide confirmation when handling user logouts

We have integrated the angular-oauth2-oidc plugin into our system. Specifically, we are using: angular 13 angular-oauth2-oidc 13.0.1 Our OAuth IDP is WSO2 Identity Server, and here is a sample of the discovery service implemented by WSO2 IS: { // ...

Implementing Custom Font Awesome Icons in Your Angular Project

I recently upgraded to a fontawesome subscription with a paid plan and have successfully created some custom icons. Now, I'm looking to integrate these icons into my angular app. Here are the dependencies listed in my package.json file: "@fortawe ...

Steps for attaching attributes to a displayed element in TileVectorLayer

As seen in the code below, I am creating a VectorTileLayer where the VectorTileSource is showing MVT geometry retrieved from a webservice specified in the url attribute. The database table includes columns as follows. The webservice will be called for each ...

What is the best way to modify an object's property before including it in a new array?

Within my Angular App, there exists a list of objects that can be added to the cart. When an item is added to the cart, I save the cart in local storage. However, a problem arises when the item is added from the product detail page where the item image is ...

Extract an array from a JSON array based on the lowest value of the keys

Consider the following array: [{ "activity" : "Hiking", "level" : "8.5" }, { "activity" : "Swimming", "level" : "-3.2" }] I want to loop through the JSON data and identify the object with the lowest value for level. In this example, I sho ...

Executing the Drag and Drop feature with Protractor

I'm looking for a way to automate drag and drop functionality in my Angular application. After following the code snippet provided in the Protractor documentation like this: browser.actions(). dragAndDrop(element1, element2). ...

Develop a customized interface for exporting styled components

I am struggling to figure out how to export an interface that includes both the built-in Styled Components props (such as as) and my custom properties. Scenario I have created a styled component named CustomTypography which allows for adding typographic s ...

Issues Arising When Trying to Call a Rest API on Express.js Using Angular 2

When I attempt an http get call from my Angular component, I encounter the following error: "Failed to load http://localhost:3005/json: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3 ...

Struggling to retrieve the 'this' object using a dynamic string

Within my Nuxt + TS App, I have a method that attempts to call a function: nextPage(paginationName: string): void { this[`${paginationName}Data`].pagination .nextPage() .then((newPage: number) => { this.getData(pagination ...

Utilizing the power of HTML datalist and *ngFor to present one value while sending another

I am currently working on a project that involves creating an autocomplete text box using the <datalist> tag with *ngFor functionality. However, the code I am using is showing both the value declared with [value] and the input between the <option& ...

Discovering if a consistent value is present in every row of an array list can be achieved using Angular

In my array list, I have a collection of values structured as follows: "data": { "input": [ { "weight": 'KG', "Amt": 40 }, { "weight": 'KG', "Amt": 20.25 }, { "weight": 'KG', "Amt": 10.30 } ] } How ...

Enhancing .gitignore with conditional logic for more efficient file exclusion

In my TypeScript project, I am facing an issue with unnecessary merge conflicts caused by the generated .d.ts and .js files. Since my project is quite large and only halfway converted from JS to TS, I cannot simply ignore all .js files using .gitignore. A ...

Adding React with TypeScript to an existing ASP.NET Core MVC application: A step-by-step guide

Can anyone suggest a reliable method to integrate react components (typescript) in the form of .tsx files into my asp.net core mvc .cshtml pages? I've been encountering issues trying to make it work successfully. Any insights or advice would be greatl ...