lakshmi mullapudi
lakshmi mullapudi

Reputation: 23

Apply formatting filter/pipe dynamically in *ngFor in Angular (Angular 2/4)?

This is my data Object in component

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

HTML

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

I need to display a table of data with each row in different format.

I am using typescript/angular4.

Upvotes: 1

Views: 1583

Answers (2)

Deepak Kumar
Deepak Kumar

Reputation: 1699

You need to create pipes.

sample(To replace ? with N):

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

@Pipe({name: 'nnn'})
export class NReplacePipe implements PipeTransform {
  transform(value: string): string {
   // write your custom logic here
    let newValue = value.replace(/\?/g, 'N');
    return `${newValue}`;
  }
}

and then use it in your html code

<p>varName |  nnn </p>

This would transform your output.

Upvotes: 1

DeborahK
DeborahK

Reputation: 60528

One option is to create a custom pipe. You could then pass your formatting string into your custom pipe. Your custom pipe would parse the passed in formatting string and perform the appropriate formatting.

Does that sound like it might work?

Upvotes: 2

Related Questions