1

How to translate angular variables in template or ts file itself
HTML code - someComponent.html

<button (click)="changeLang('en')">En</button>  
<button (click)="changeLang('de')">de</button>  
<p>{{rate}}</p>

Ts File - someComponent.ts

rate:string="productRate";
changeLang(lang){  
  this.translate.use(lang);
  this.traslate.get(this.rate).subscribe(res=>{this.rate = res;});
}  

Json file-en.json

{ "productRate": "Product Rate" }  

Json file-de.json

{ "productRate": "Produktpreis" }  

I know how to do it in template using pipe but unable to do it in ts.
I had referenced stack overflow but unable to get the result. Please help

2
  • 1
    Are you using a library ? If so, state this in your question Commented Jul 26, 2018 at 9:34
  • I am sorry for that. Yes I am using @ngx-translate/core Commented Jul 26, 2018 at 9:36

1 Answer 1

2

From Docs

get(key: string|Array, interpolateParams?: Object): Observable: Gets the translated value of a key (or an array of keys) or the key if the value was not found

You have to inject TranslateService as a dependency and do it as,

constructor(private translate: TranslateService) {
    let foo:string = this.translate.get('productRate');
}
Sign up to request clarification or add additional context in comments.

3 Comments

I injected the service sajeeth, to keep it simple I had posted without that.
what do you mean
this.traslate.get('productRate').subscribe(res=>{this.rate = res;}); this will work. because translate.get returns observable.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.