Best string practice in Angular 2

I studied Angular 2 and wondered what is considered best practice for storing strings. I use various lines throughout the application: some of them are placed directly in HTML elements, for example,

// sample.html <h1>This is my title</h1> 

other lines are stored in component models that are linked, for example,

 // boundSample.html <h1>{{myTitle}}</h1> // boundSample.component.ts import ... @Component({ templateUrl: 'boundSample.html'; }) export class BoundSampleComponent { myTitle = 'This is another title'; } 

My concern is that my lines are distributed throughout the application. Based on the C # / WPF background, I use to store strings in one place (e.g. strings.xaml ), which I can import into code markup and UI (i.e. XAML for WPF, HTML for Angular). This helps a lot in maintainability and internationalization.

In addition, a quick look at internationalization in Angular 2 involves the use of the i18n attribute and the i18n tool . This assumes that all of my lines are defined in HTML, but what if I want to use some of these lines in code ...

How and where can I define one place for my lines in Angular2 so that I can access these lines in my code and use internationalization tools?

+6
source share
1 answer

You can search for some tools, some of them are good and already realize what you want to have. However, if you want to do it the way you are used to, follow these steps:

  • Save the lines in the XAML / JSON / YAML / etc file where you store your lines. If you use webpack, use the appropriate loader that processes the material for you. If not, you will need to analyze this file yourself.

  • Create a service that can get information from a file (in the constructor, I think), and has a function that returns a string based on the string token.

  • Create a channel that returns a string based on the token.

  • Use the feed in HTML and the service in typescript files.

i18n - no problem, just pass the language to the service function / subscribe to the language change observed in the service.

The implementation is trivial. But think twice: you can use existing solutions.

+2
source

Source: https://habr.com/ru/post/1013413/


All Articles