angulartypescriptangular-translatengx-translate

How to use functions in a inline HTML translate pipe?


My goal is to minimize the code using the Angular translate pipe. Currently, I have to use 8 curly brackets and write "translate" twice... a better way must exist.

My current code looks like:

<span
  *ngIf="checkoutForm.get('email')?.errors?.['email']">
  {{ 'eMail' | translate }} {{ lowerCaseFirstLetter('isInvalid' | translate) }}
</span>

And I'm trying to do shorten it in something like

<span
  *ngIf="checkoutForm.get('email')?.errors?.['email']" 
  translate>eMail {{ lowerCaseFirstLetter('isInvalid' | translate) }}
</span>

or maybe even

<span
  *ngIf="checkoutForm.get('email')?.errors?.['email']"
   translate>eMail lowerCaseFirstLetter('isInvalid')
</span>

The Text

email is a translation = E-Mail
isInvalid is a translation = Is invalid
lowerCaseFirstLetter() is a function which just lowercases first letter this is important to not destroy the orthography in other languages


Solution

  • You could create a custom pipe that accepts an extra parameter so you can do this:

    <span
        *ngIf="checkoutForm.get('email')?.errors?.['email']"> 
        {{ 'eMail' | error:'isInvalid' }}
    </span>
    

    for that create a pipe file error.pipe.ts with following content:

    import { Pipe, PipeTransform } from '@angular/core';
    import { TranslateService } from '@ngx-translate/core';
    
    @Pipe({
              name: 'error'
    })
    
    export class ErrorPipe implements PipeTransform {
              constructor(private translateService: TranslateService) {
              }
              transform(value: string, arg: string): string {
                        return `${this.translateService.instant(value)} ${this.translateService.instant(arg).toLowerCase()}`;
              }
    }
    

    declare it in the component module you want to use it in example.module.ts:

    import { NgModule } from '@angular/core';  // standard
    import { CommonModule } from '@angular/common';  // standard
    import { ErrorPipe } from './path/to/error.pipe';
    
    @NgModule({
      imports: [CommonModule, ExampleRoutingModule], // standard
      declarations: [ExampleComponent, ErrorPipe]
    })
    export class ExampleModule {}
    

    now you can do following thing in the component:

    <span
        *ngIf="checkoutForm.get('email')?.errors?.['email']"> 
        {{ 'eMail' | error:'isInvalid' }}
    </span>