On angluar, how to use pipe on parameters used in translation

114 Views Asked by At

I have to display a lot of texts to translate with parameters. Some parameters are dates, some are numbers, some are currencies, etc. Is there a way to "nest" the angular pipes?

I know I can create a proxy object in the component with the variable already transformed. But I'd prefer to only use these 'display' pipes in the hhtml. In a perfect world, I would have a translation:

'my_text' : "This object was bought on {{my_date | date}} for {{amount | currency}} with a discount of {{discount | percent}}"

an object:

const my_object = {my_date: new Date(), amount: 30000, discount: 0.1}

and use it in the html:

{{'my_text' | translate : my_object}}

Is there a way to do something close to this solution? A custom translate pipe maybe ?

1

There are 1 best solutions below

1
Jivopis On

You should write a custome pipe of your custom object not string value. Example of pipe in the format that you want:

import { Pipe, PipeTransform } from '@angular/core';
import { formatCurrency, formatPercent, formatDate } from '@angular/common';

@Pipe({ name: 'mypipe', standalone: true })
export class Mypipe implements PipeTransform {
  // adding a default format in case you don't want to pass the format
  // you can add extra parameters into transform if needed
  transform(
    data: any,
    locale: string,
    dateFormat: string,
    currency: string
  ): string {
    // do your stuff
    let retValue =
      'This object was bought on ' +
      formatDate(data.my_date, dateFormat, locale);
    retValue += ' for ' + formatCurrency(data.amount, locale, currency);
    retValue += ' with a discount of ' + formatPercent(data.discount, locale);
    return retValue;
  }
}

modify your html to take parameters for localization and else:

<span>{{my_object| mypipe: 'en-US' : 'mm/dd/yyyy': '$'}}</span>

Response will be:

This object was bought on 45/07/2023 for $30,000.00 with a discount of 10%

Check the sandbox below: https://stackblitz.com/edit/stackblitz-starters-ja11lr?file=src%2Fmain.ts

You always can do next in html to avoid opf creating custom pipes:

<span>This object was bought on {{my_object.my_date | date}} for {{my_object.amount | currency}} with a discount of {{my_object.discount | percent}}</span>