ngx-translate在Angular 7中使用变量作为参数

时间:2019-06-25 15:09:41

标签: angular ngx-translate

我在Angular7中遇到NGX-Translate问题。

我正在尝试翻译带有参数的短语。如果参数是硬编码的,则可以使用,但是如果参数是变量,则不会。

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)",
}

以下是stackBlitz

上的示例

1 个答案:

答案 0 :(得分:1)

这是因为days: '30'。您没有正确初始化days,只是将其类型设置为'30',这意味着您无法设置days以外的'30'

我认为这是一个错字。将其更改为days = '30'