Is it possible to apply a formatting filter or pipe dynamically within an *ngFor loop in Angular (versions 2 and 4

Here is the data Object within my component

sampleData=[
  {
    "value": "sample value with no formatter",
    "formatter": null,
  },
  {
    "value": "1234.5678",
    "formatter": "number:'3.5-5'",
  },
  {
    "value": "1.3495",
    "formatter": "currency:'USD':true:'4.2-2'",
  }
]

HTML Snippet

<div *ngFor="let data of sampleData">{{data.value | data.formatter}}</div>

I am in need of displaying a table which showcases each row with different formatting.

The technology I am utilizing is typescript along with Angular 4.

Answer №1

Have you considered implementing a unique filter? By utilizing a custom filter, you have the ability to input your desired formatting string. The filter can then interpret and apply the specified formatting accordingly.

Do you think this approach could be effective for your needs?

Answer №2

To solve the problem, you must develop pipelines.

Example(Replacing ? with N):

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'replaceQuestionMark'})
export class ReplaceQuestionMarkPipe implements PipeTransform {
  transform(value: string): string {
    // Add your specific logic here
    let updatedValue = value.replace(/\?/g, 'N');
    return `${updatedValue}`;
  }
}

Next, implement it in your HTML code

<p>varName | replaceQuestionMark </p>

This will alter your result accordingly.

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

How can I retrieve distance data from the Google Maps API within an Angular service?

I am currently working on implementing the JavaScript version of the Google Maps API in order to resolve a CORS issue that I encountered with the regular API. Specifically, I am looking to calculate the distance and time between two destinations. How can I ...

Angular4 interceptor modifying the response

I've implemented an HttpInterceptor: import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http'; import {AuthService} from '../service/auth.service'; import {Observable} from &apo ...

Observable map encounters an error when attempting to retrieve essential data from the backend server

Here is my approach: getDropdownData(id: number | 195731): Observable<ClinicTrialSettingProp> { return this.http .get<ClinicTrialSettingProp>(this.commonPatientURL + id + '/clinic-trials') .pipe(map(response => res ...

There was an issue encountered when creating the class: The parameters provided do not correspond to any valid call target signature

I am facing an issue with my code. Here is the scenario: export class MyClass { public name:string; public addr:string; constructor() {} } I have imported MyClass and trying to use it like this: import { MyClass } from './MyClass' ...

Limiting the character input in ion-textarea within Ionic 2: A step-by-step guide

In my Ionic 2 application, I need to limit user comments to less than 500 characters in a text area. What is the best way to implement this restriction? ...

Exploring the Depths of JSON Arrays within Typescript

I am faced with a challenge in extracting the value of the "id" from the following array of JSON data. The issue lies in the fact that the value is enclosed within double square brackets "[[" which are causing complications in retrieving the desired result ...

Troubleshooting the issue with Angular, express, and nodemailer functionality

When I implement the combination of components in a separate project, it works perfectly fine with just the app.component. However, integrating it into the website project I'm currently working on seems to cause issues. The main problem arises when I ...

tips for accessing the useState value once it has been initialized

When using the state hook in my code, I have: const [features, setFeatures] = useState([]) const [medicalProblem, setMedicalProblem] = useState([]) The medicalProblem variable will be initially populated with a response from an API call: useEf ...

Steps for clicking on the center of a leaflet map with protractor

I'm currently facing an issue where I am attempting to click on the center of a map located in the second column of the webpage, which has an offset. However, I am encountering a problem where the cursor always points to the center of the page instead ...

Tips for outputting data in TypeScript when a search form is updated

Below is the structure of my HTML file: <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type"" content="text/html; charset=utf-8"/> </head> <body> <input ...

timer-based user session expiration

Currently, the app I'm developing has a system where a session is created with a 15-minute expiration time once a user interacts with a form. This session is managed server-side. If the user remains idle for 15 minutes, the server returns a 404 erro ...

Utilizing the output of one function as an input parameter for another function: A guide

Having this specific shape const shape = { foo: () => 'hi', bar: (arg) => typeof arg === 'string' // argument is expected to be a string because foo returns a string } Is there a way to connect the return type of foo to the ...

Angular 6 - Separate whole numbers and decimal values to style them differently in CSS

Is there a way in Angular to format a price so that the cents/decimal part appears as a superscript? What would be the most effective approach in Angular to achieve this based on the initial setup below? export class PriceComponent implements OnInit { ...

Testing files outside of the project directory in Angular + Karma can present challenges in performing thorough analysis and evaluation

I have a file structure set up as follows: projects myproj - Angular App myproj-lib - Angular Library shared - shared code used in both the app and the library Both the App and Lib projects were created using Angular CLI (angular.json has not been mo ...

Tips on implementing npm's node-uuid package with TypeScript

Whenever I attempt to utilize node-uuid in TypeScript, I encounter the following issue: Cannot find module uuid This error occurs when I try to import the uuid npm package. Is there a way to successfully import the npm uuid package without encountering ...

What does the "start" script do in the package.json file for Angular 2 when running "concurrent "npm run tsc:w" "npm run lite"" command?

What is the purpose of concurrent in this code snippet? "scripts": { "tsc": "tsc", "tsc:w": "tsc -w", "lite": "lite-server", "start": "Concurrent npm run tsc:w npm run lite" } ...

The negation operator in Typescript is failing to negate as expected

When a user changes a multiselect element, there is a function that runs to control the visibility of an error message: getVisibility(multiselect) { if ((multiselect.selectedCategories.length < 1 && !multiselect.allSelected) && th ...

Webpack is struggling to locate core-js paths when running on Windows operating systems

When running webpack, I am encountering the following errors: ERROR in ./node_modules/core-js/index.js Module not found: Error: Can't resolve './es' in 'pathtoproject\node_modules\core-js' @ ./node_modules/core-js/index. ...

Typescript/Three.js encounters the issue of game objects becoming undefined

Something in my code seems to have broken unexpectedly. I can't figure out why the "Game" object is defined before calling this.render() in the constructor, but becomes undefined in the render method. Before render(), the console shows: Game camera: ...

Ways of invoking a component method from a service in Angular 2

I have a concept for creating a unique service that is capable of interacting with one specific component. In my application, all other components should have the ability to call upon this service and then have it interact with the designated component in ...