Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8 i18n translate dynamic variable

I have in my app.component.html an element that is on every page:

<h1 i18n="@@titleH1">{{title}}</h1>

I have a shared service that has a setters and getters:

...
title = new BehaviorSubject('Initial Title');

setTitle(title: string) {
this.title.next(title);
}
...

app.component.ts: ngOnInit

...
this.sharedService.title.subscribe(updateTitle => this.title = updateTitle);
this.sharedService.setTitle('Dashboard');
...`

product.component.ts: ngOnInit

...
this.sharedService.title.subscribe(updateTitle => this.title = updateTitle);
this.sharedService.setTitle('Product');
...

When navigate to /dashboard I get Dashboard in the when I navigate to /product I get Product in the which is cool.

How can I translate Dashboard and Product Dinamically as {{title}} will change according to the page.

my xlf produced this:

     ... 
     <trans-unit id="titleH1" datatype="html">
        <source><x id="INTERPOLATION" equiv-text="{{title}}"/></source>
        <target><x id="INTERPOLATION" equiv-text="{{title}}"/></target>
        <context-group purpose="location">
          <context context-type="sourcefile">src/app/app.component.html</context>
          <context context-type="linenumber">17</context>
        </context-group>
      </trans-unit>
      ...

and I added the target tag but not sure how this fit into translation.

Any Ideas. Thanks

like image 228
Juliano Avatar asked Sep 09 '26 18:09

Juliano


1 Answers

There is Angular 9 with the new $localize which makes it possible to do like so.

app.component.html:

<h1>{{title}}</h1>

app.component.ts:

...
title = $localize`:@@dashboard:Dashboard`;
...
this.sharedService.setTitle(this.title);

product.component.ts:

...
title = $localize`:@@product:Product`;
...
this.sharedService.setTitle(this.title);

messages.xlf:

<trans-unit id="dashboard">
  <source>Dashboard</source>
  <target>Translation here</target>
</trans-unit>
<trans-unit id="product">
  <source>Product</source>
  <target>Translation here</target>
</trans-unit>

Nice @Angular team!

like image 147
Juliano Avatar answered Sep 11 '26 08:09

Juliano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!