I'm having an issue with NGX-Translate in Angular7.
I'm trying to translate a phrase with a parameter. If the parameter is hardcoded, it works, but if the parameter is a variable it doesn't.
app.component.ts
import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
hardcoded: string;
fromVariable: string;
days: '30';
constructor(private translate: TranslateService) { }
ngOnInit() {
this.translate.setDefaultLang('en');
this.translate.use('en');
// Value Hardcoded - THIS WORKS
this.translate.get('UPCOMING_RENEWALS', { output: '30' }).subscribe((s: string) => {
this.hardcoded = s;
});
// value from variable - THIS DOESN'T
this.translate.get('UPCOMING_RENEWALS', { output: this.days }).subscribe((s: string) => {
this.fromVariable = s;
});
}
}
app.component.html
<h1>
{{ 'UPCOMING_RENEWALS' | translate :{output:'30'} }}</h1>
outputs: Upcoming Renewals (30 days)
<h1>{{hardcoded}}</h1>
outputs: Upcoming Renewals (30 days)
<h1>{{fromVariable}}</h1>
outputs: Upcoming Renewals ({{output}} days)
en.json
{
"UPCOMING_RENEWALS": "Upcoming Renewals ({{output}} days)",
}
Here is a sample on https://stackblitz.com/edit/angular-failing-translate-variable
NGX-Translate is an internationalization library for Angular. Internationalization is the process of translating an application into multiple languages. Using this library, we can translate our application language into multiple languages. This will work with not only static data, but dynamic data as well.
The service also contains a method called translate. It is later called by the pipe to get the translation for a specific key. It always uses the language specified in the 'language'-variable of the service, to lookup the translation. That's it.
It is because of days: '30'
. You didn't initialize days
correctly, you just set it's type to '30'
which means you cannot set days
other than '30'
.
I assume this is a typo. Change it to days = '30'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With