Angular 4 i18n get translation for TS / JS code also

I use the default i18n process for my Angular 4 project, so I use ng-i18n to create .xlf without any problems.

But in my typescript code, I also have some texts that need to be translated and obtained by id for the current language.

I cannot find a way to do this in Angular 4. Am I missing something? I use AOT if this is important.

The problem can also occur if the server sends a message / error code from web services, how to translate them using Angular

+5
source share
2 answers

Currently, it is not yet possible to translate from i18n from typescript code.

"Angular only supports i18n in your templates, I am working on a function that will allow you to use it in your code, but it still works. This library works both in code and in templates" (Olivier Combe, Angular contractor Core Team)

Have a look at this discussion: https://github.com/ngx-translate/core/issues/495

+2
source

here is my decision to translate my warning message when ngx-toastr is called inside my ts file, I created a link in the template with i18n and use this element for my message with html enabled

 ngOnInit() { this.toastrService.success('created successfully', ''); } 

I converted it to this

 @ViewChild('successContainer ') successContainerRef: ElementRef; ... constructor(private toastrService: ToastrService) {} ngOnInit() { this.toastrService.success(this.successContainerRef.nativeElement.outerHTML, '', { enableHtml : true }); 

and in my template I create a div with the link #successContainer

 <h2 i18n="@@successMessage" #successContainer [hidden]="true">created successfully</h2> 
0
source

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


All Articles