ngx-translate using a variable as a parameter in Angular 7
Asked Answered
A

1

10

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

Altricial answered 25/6, 2019 at 15:9 Comment(0)
T
10

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'

Tanberg answered 25/6, 2019 at 15:13 Comment(1)
Thank you. Sorts it perfectly. I looked at that for an hour, and then copied it to the stackBlitz example and still didn't see it.Altricial

© 2022 - 2024 — McMap. All rights reserved.