Greg-A
Greg-A

Reputation: 862

How to translate the title of a tooltip with ngxTranslate

I use the bootstrap tooltip like this :

<em class="fas fa-hand-paper cursor-pointer" data-toggle="tooltip" data-placement="top" title="{{displayMessage(statut)}}" [attr.aria-label]="displayMessage(statut)"></em>

For the title of the tooltip I use a function which returns me a different value according to the parameters :

title="{{displayMessage(statut)}}"

and :

public tooltipMessage: string;


public displayMessage(value) {
 if (value != null) {
   this.translate
     .get(`TOOLTIP.ICON.${value}`)
     .subscribe((res: string) => {
       this.tooltipMessage = res
       return this.tooltipMessage;
     })
  }
console.log(this.tooltipMessage);
}

For the translation I use ngx-translate for two languages.

The problem:

When I switch to the tooltip the title is displayed according to the language but when I change the translation the title of the tooltip does not reset, I have to reload the page to display the title translated in the correct language.

I tried using the "onLangChange" function of ngx-translate.

 public ngOnInit() {
  this.subscriptions.add(
   this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
    this.displayMessage(this.statut);
  })
 );
}

But unfortunately without success

The most astonishing if I control the console.log(this.tooltipMessage); this last returns the translation well but does not update the html.

Do you have a solution for this problem?

Upvotes: 1

Views: 1815

Answers (1)

Askirkela
Askirkela

Reputation: 1209

Use the ngx-translate translatePipe pipe (and replace your displayMessage(...) method with a pipe):

title="{{statut | displayMessage | translate}}" or

[title]="statut | displayMessage | translate"

If your displayMessage method/pipe returns a translation key, it will be translated.


Edit for clarity

Create a Pipe for displayMessage

@Pipe({name:'displayMessage'})
export class DisplayMessagePipe {
  transform(value: string) {
    return value != null ? `TOOLTIP.ICON.${value}` : '';
  }
}

then use the newly create pipe in your template:

<em
  class="fas fa-hand-paper cursor-pointer"
  data-toggle="tooltip"
  data-placement="top"
  [title]="statut | displayMessage | translate"
  [attr.aria-label]="statut | displayMessage | translate">
</em>

ngx-translate's TranslatePipe takes care of using your translation key to look-up the corresponding text in the current lang

Upvotes: 2

Related Questions