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

John McArthur picture John McArthur · Jun 25, 2019 · Viewed 11.8k times · Source

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

Answer

Bunyamin Coskuner picture Bunyamin Coskuner · Jun 25, 2019

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'