Home > Blockchain >  How to use functions in a inline HTML translate pipe?
How to use functions in a inline HTML translate pipe?

Time:11-14

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

CodePudding user response:

Not 100% certain about your question, but assuming you want to show the translation of an error message that contains the topic (in your example ‘eMail’) and the specific error (in your example about being invalid).

You can create your own pipe for printing translated error messages that (under water) calls the existing other pipes via typescript code instead of via template.

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

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

CodePudding user response:

you can create a translate directive like the 3 code block

@Directive({
  selector: '[translate]'
})
export class TranslateDirective implements AfterViewInit {

  constructor(private el: ElementRef) { }

   ngAfterViewInit() {
    const translatedText = translate(this.el.nativeElement.innerText)
    this.el.nativeElement.innerText = translatedText;
  }
}
<span
  *ngIf="checkoutForm.get('email')?.errors?.['email']"
   translate>eMail lowerCaseFirstLetter('isInvalid')
</span>
  • Related