String Resources in Angular

Viewed 12977

I'm developing an Angular app and I'm looking for something similar to Android Resource available in Android development.

Here is the way to get a string in Android:

String mystring = getResources().getString(R.string.mystring);

I would like to have the same in Angular.

For example if I have few HTML templates in which there are the same message about the wrong email provided...

<div class="alert alert-danger">
      <strong>Error!</strong>Invalid e-mail
</div>

I would like to have the following:

<div class="alert alert-danger">
      <strong>Error!</strong>{{myStrings.INVALID_EMAIL}}
</div>

...or something like this...

<div class="alert alert-danger">
      <strong>Error!</strong>{{'INVALID_EMAIL' | stringGenerator}}
</div>

Do you know a way or addon I can install to reach that?

3 Answers

AndreaM16's answer is definitely thorough, but you sould also consider using an existing package for this instead of writing your own custom code that you need to maintain. To that end, I would recommend checking out ngx-translate (which is used somewhat under the hood in that answer), transloco and Angular's built-in i18n capabilities.

Most of those approaches are based on the magic strings, where your HTML templates and typescript code need to contain strings that (hopefully) match the keys in a JSON or XML file. This presents a serious code maintenance issue which won't be revealed at compile time, only at runtime. I would also advocate for checking out some guides on creating a type-safe translation system:

You can also use enum file for string values.

string.ts

export enum TEST_STRING {
   TEST_ONE = "this is first test string",
   TEST_TWO = "this is second test string",
   TEST_THREE = "this is third test string"
}

component.ts

import { TEST_STRING } from '../resources/string';

var testString = TEST_STRING.TEST_ONE;   
console.log(testString);                // result = this is first test string
Related