Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngx-translate using a variable as a parameter in Angular 7

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

like image 506
John McArthur Avatar asked Jun 25 '19 15:06

John McArthur


People also ask

How does Ngx translator work?

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.

What is the use of translate pipe in Angular?

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.


1 Answers

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'

like image 194
Bunyamin Coskuner Avatar answered Nov 12 '22 03:11

Bunyamin Coskuner