You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 18中TypeScript的复数国际化支持问题求助

Angular 18 TypeScript 中实现@angular/localize复数国际化方案

Angular 18完全支持TypeScript中使用@angular/localize实现ICU复数格式国际化,你的问题源于写法不符合标签模板语法要求,以下是正确实现方式:

正确写法(标签模板语法)

必须使用标签模板语法($localize `...`)包裹国际化文本,动态变量与ICU规则需放在${}占位符内,示例代码:

import '@angular/localize/init';

const count = 1; // 可替换为动态数值
const i18NValue = $localize `@@MessageID:Found ${count, plural, =1 {item} other {items}}`;

写法说明

  • 避免使用$localize:@@MessageID:xxx;的静态字符串形式,这种写法无法解析TS中的动态ICU规则,会被识别为纯文本。
  • 标签模板语法中,${count, plural, ...}会被Angular正确解析为ICU复数规则,提取翻译单元时会自动转换为标准ICU格式。

提取后的翻译单元格式

执行ng extract-i18n后,生成的翻译条目会是标准ICU格式,示例:

<trans-unit id="MessageID" datatype="html">
  <source>Found {VAR_PLURAL, plural, =1 {item} other {items}}</source>
  <target/>
</trans-unit>

该格式会被翻译工具正确识别,你可以在目标语言文件中对应修改复数表述。

扩展示例(多复数场景)

如果需要更复杂的复数逻辑(比如0、1、其他场景),可以这样写:

function getFoundItemsText(count: number): string {
  return $localize `@@foundItems:Found ${count, plural,
    =0 {no items}
    =1 {one item}
    other {{{count}} items}
  }`;
}

// 调用示例
console.log(getFoundItemsText(0)); // 输出 Found no items
console.log(getFoundItemsText(3)); // 输出 Found 3 items

内容的提问来源于stack exchange,提问作者Gokul Raj Shanmugam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 19:24:57