【问题标题】:Angular Translate: Using .replace in an interpolation string in HTMLAngular Translate:在 HTML 的插值字符串中使用 .replace
【发布时间】:2023-03-17 02:10:02
【问题描述】:

我正在尝试结合插值和角度翻译从几个 json 文件中检索来自 en -> fr 的语言翻译。然而,所有定义都被定义为在 HTML 中显示插入的字符串,如下所示:

{{ 'this.section.in.json.' + object.param | translate}}

所以它将参数作为字符串,在 en.json 中找到它,如果设置是法语,在 fr.json 中找到翻译。 我的问题是 Object.param 来自 API,它有一个空格,而 json 的结构不同:

Need param with no spaces--> "thisString": "this String" <--Object.Param returns this

我可以在我的组件中定义一个函数来使用 .replace() 并返回一个新值,但是对于很多不同的参数,有很多不同的翻译需要处理。有没有办法在 html 文件的插值字符串中使用 .replace ?如下图

{{ 'this.section.in.json.' + object.param.replace(*regex*, '') | translate}}

【问题讨论】:

  • 是的,您可以使用 Javascript 函数,但不能使用全局 JavaScript 变量函数,如窗口、文档等。

标签: html angular interpolation translate ngx-translate


【解决方案1】:

我会做一个去除空白的新管道。 请务必将其注册到您的应用模块中。

import { Component, Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'stripSpaces' })
export class StripSpaces implements PipeTransform {
  transform(str: string): any {
    return str.replace(/\s/g, '')
  }
}

然后在你的模板中使用这个

  {{ 'this.section.in.json.' + object.param | stripSpaces | translate }}

【讨论】:

  • 两个答案都很好,但这个更完整。无论如何,谢谢你们~
【解决方案2】:

不,您不能直接在插值上下文中使用这些方法函数。但是你可以链接管道。这意味着您可以先编写自己的管道来删除这些空格,然后再应用您的翻译。

例如:

{{ 'this.section.in.json.' + object.param | removeWhitespaces | translate}}

在这里,您首先删除空格,然后翻译“清理”字符串。

【讨论】:

    猜你喜欢
    • 2018-12-18
    • 2015-02-02
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-20
    相关资源
    最近更新 更多