We have to wait until Angular 6 for angular-i18n to support translations in code for error messages and such.
For those that are using angular-i18n (instead of ngx-t
It has been a long time since my last response and it can be simplified.
if our .html is like
We have in our .ts a simple ViewChildren, a variable "yet" and a variable "translation"
yet: boolean = false;
translation:any={}
@ViewChildren("t")
set translations(values: QueryList) {
//when yet becomes true, values.length=0
if (values.length) {
values.forEach(c => {
this.translation[c.nativeElement.id]=c.nativeElement.innerHTML
})
//it's necesary enclosed this.yet=true in a setTime to avoid
//the error expresion changes After Exec
setTimeout(()=>{
this.yet=true;
})
}
}
then we can write some like
alert(this.translation['message1']);
Update The same idea: a component implementation you have a component
import { Component, QueryList, AfterViewInit, ContentChildren } from '@angular/core';
@Component({
selector: 'ng-translation',
template: `
`
})
export class TranslationComponent implements AfterViewInit {
@ContentChildren("t") translations: QueryList
data: any = {}
yet: boolean = false;
get(text: string) {
return this.data[text];
}
ngAfterViewInit(): void {
if (this.translations.length) {
this.translations.forEach(c => {
this.data[c.nativeElement.id] = c.nativeElement.innerHTML
})
setTimeout(() => {
this.yet = true;
})
}
}
}
In any other component
Translation app
Hola Mundo
@ViewChild("translation") translation:TranslationComponent
click()
{
alert(this.translation.get('message1'));
}
Example in stackblitz