With new Angular 9 @angular/localize is now possible to translate code directly from typescript. As its usage is not officially well documented, I found some tips on this post.
$localize`:@@my-trans-unit-id:` // IT WORKS
That works correctly when ID is directly passed to the function, but if I want ID to be dynamic (and pass a variable), it does not work, rendering ID without parsing nor translating.
I tried it by passing the variable this way:
const id = "my-trans-unit-id";
$localize`:@@${id}:`; // NOT WORKING
$localize`:@@`+id+`:`; // NOT WORKING
Angular does not provide any mechanism to generate dynamic translations as they are generated at compile time.
I ended up creating pipes and calling them every time I need a translation. Instead of using 1 unique instruction to translate the string, I use multiple $localize
calls inside a switch to return proper translation by ID.
This is an example for translating order status that can be called on runtime:
import { Pipe, PipeTransform } from '@angular/core';
import { OrderStatusEnum } from 'installation-status.enum';
@Pipe({
name: 'orderStatusRenderer'
})
export class OrderStatusRendererPipe implements PipeTransform {
constructor() {}
transform(value: number, ...args: any[]): any {
switch (value) {
case OrderStatusEnum.PREPARING:
return $localize`:@@order.status.preparing:`;
case OrderStatusEnum.SHIPPED:
return $localize`:@@order.status.shipped:`;
case OrderStatusEnum.COMPLETED:
return $localize`:@@order.status.completed:`;
}
}
}
This works.
Don't ask me to explain, I got this by trial and error:
const localize = $localize;
const id = "my-trans-unit-id";
const translation = localize(<any>{ '0': `:@@${id}:${id}`, 'raw': [':'] });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With