Angular: Translate Enums (i18n)
--
One of the biggest flaw of built-in Angular translation engine is it only supports translations known during build time. Moreover, only known in HTML template.
One common struggle is translating calculated values like enums in TypeScript.
Good news for you: It’s quite easy if you follow one practice.
Problem — translate model from server
To make things easy to reason about, let’s have a Todo App :)
With usage:
So what is the problem?
{{ items.state }}
will produce generated enums values (0, 1, 2... or 'TODO', 'IN_PROGRESS'...)- We need to convert enum value into string, however this has to be within template, not TypeScript
Bad solution
We tend to create method with switch-case, which is unfortunate because Angular i18n is not aware of those strings, and so — it won’t touch them during translation.
How to make it translatable?
There is only one rule to follow:
Every string visible in UI has to be put in template
Usually in our team, for complex string calculation (enums, or some text logic) we create new component responsible only for translation.
This approach initially seem like — meh, overkill. But it has advantage We’re using it widely in our applications, making a clear distinction between screen-logic and text-logic.
Solution #1
- This works only with regular enums,
const enum
cannot be used within template (at least, not out of the box) - We happily use this practice not only for enums, but also for string manipulations.
- You still need to remember to update template when new enum values are added (e.g.
TodoState.BLOCKED
)
Solution #2 — ICU messages
- Works with const enums
- Useful especially for string enums
- Simpler approach and also supports HTML elements e.g.
TODO {<span>not</span> started}
) - To be secure, you need to write unit tests that checks enum values
Final usage
<todo-state-i18n> component to print item state
Bonus — test checking all enum values
Do you have more struggles with built-in Angular i18n?
If you’ve learned something new, please:
→ clap 👏 button below️ so more people can see this
→ follow me on Twitter (@constjs) so you won’t miss future posts: