首页 > 解决方案 > 在Angular 7中使用变量作为参数的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)",
}

这是https://stackblitz.com/edit/angular-failing-translate-variable上的示例

标签: angularngx-translate

解决方案


这是因为days: '30'. 您没有days正确初始化,您只是将它的类型设置为,这'30'意味着您不能设置.days'30'

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


推荐阅读