【问题标题】:How to use translation in a directive field?如何在指令字段中使用翻译?
【发布时间】:2019-02-22 19:19:26
【问题描述】:

我正在构建一个 Angular 应用程序,我想在我的整个应用程序中添加翻译。为此,我使用ngx-translation method。使用参数构建翻译时遇到问题:我的应用显示 [Object object]。 我使用了一个使用 [message] 字段的指令,该值需要翻译,但我不知道如何在我的消息值中添加翻译。

我的组件如下:

<app-confirmation-dialog  
[translate]="'demo.greeting'" 
[translateParams]="{name: 'Andreas'}"
[message]="?????????"
[confirmationLabel]="'quit anyway'"
(onConfirmation)="onCancel()"></app-confirmation-dialog>

我在翻译文件中添加了相同的键:

{
  ....
  "demo": {
    "greeting": "Hello {{name}}!"
  }
  ....
}

你有什么想法在我的消息值中添加翻译吗?

【问题讨论】:

    标签: angular translation ngx-translate


    【解决方案1】:

    在这种情况下,您将无法轻松使用指令形式的翻译,因为您将 message 作为元素的属性传递(在这种情况下,是指令的输入)。如果您继续使用指令形式[translate],那么它会以您不希望的方式与您自己的指令混淆。

    改为使用管道形式,将参数对象作为参数传递:

    <app-confirmation-dialog
      [message]="'demo.greeting' | translate: {name: 'Andreas'}"
      [confirmationLabel]="'quit anyway'"
      (onConfirmation)="onCancel()">
    </app-confirmation-dialog>
    

    【讨论】:

    • 非常有帮助,谢谢
    • 当我们在消息字段中有一个函数时会发生什么? `[confirmationLabel]="getConfirmationLabelOfPromptDialog()" 并且在 component.ts 文件中你有这个:getConfirmationLabelOfPromptDialog(): string { return "I'm done"; }
    • 对不起,我在上一个问题中忘记了你的身份@zicon
    • @shtb2708 我以前从来没有做过,但据我所知应该像[confirmationLabel]="getConfirmationLabelOfPromptDialog() | translate"一样简单
    • 我试过这种方式,它只是在屏幕上显示getConfirmationLabelOfPromptDialog()函数@zircon,你可能知道编码的方式,谢谢你的帮助,如果你找到解决方案我会很高兴知道它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 2017-09-21
    • 1970-01-01
    • 2015-09-05
    • 2018-11-13
    相关资源
    最近更新 更多