Home > Mobile >  Angular Boolean Pipe Yes/No localized
Angular Boolean Pipe Yes/No localized

Time:06-12

i need a handy way to get my yes-no pipe localized like the date pipe {{ my.date | date: 'short' : 'UTC' : 'de-DE' }}

something like

    {{ my.boolean | yesNo : "de-DE" }}

and instead of returning value ? "Yes" : "No"; I need some magic :D

    @Pipe({
      name: 'yesNo'
    })
    export class YesNoPipe implements PipeTransform {
    
      transform(value: boolean, ...args: unknown[]): string {
        // need some magic
        return value ? localizedYes : localizedNo;
      }
    
    }

CodePudding user response:

Unfortunately, unlike Date which can be easily localize using JS, a simple "Yes" or "No" string have to be translated in order to achieve this. Here are some of the steps that I would go to achieve this:

  1. Instal ngx-translate https://www.npmjs.com/package/@ngx-translate/core and follow their guide for setup as well as create the translation resource files for all the languages that you want to be translated. If you don't like their documentation, here's a great article with an easy to follow guide https://www.codeandweb.com/babeledit/tutorials/how-to-translate-your-angular-app-with-ngx-translate
  2. The rest is just using the translate service together with your pipe
    @Pipe({
      name: 'yesNo'
    })
    export class YesNoPipe implements PipeTransform {
    
      transform(value: boolean, ...args: unknown[]): string {
        return value ? 'KEY.YES' : 'KEY.NO';
      }
    
    }
    ...
    {{ my.boolean | yesNo | translate }}

It's a bit of a pain but this setup will scale infinitely for any future work that require localization/globalization.

  • Related