Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $localize using dynamic translation ID

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
like image 498
Gothem Avatar asked Mar 31 '20 15:03

Gothem


2 Answers

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:`;
        }
    }
}
like image 73
Gothem Avatar answered Oct 18 '22 20:10

Gothem


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': [':'] });
like image 22
Guilherme Meinlschmiedt Abdo Avatar answered Oct 18 '22 20:10

Guilherme Meinlschmiedt Abdo