【问题标题】:How to write a string.format(...) for value of an HTML attribute?如何为 HTML 属性的值编写 string.format(...)?
【发布时间】:2020-05-19 19:32:03
【问题描述】:

我创建了一个数据列表,其标签的格式为:“城市名称(城市代码)”

<!-- Sélecteur de communes du COG -->
<input type="text" list="communesCOG" [(ngModel)]="commune" (click)="selectCodeCommune(commune)">
<datalist id="communesCOG" >
    <option *ngFor="let commune of communes | keyvalue"
        [value]="commune.value.codeCommune"
        [label]="commune.value.nomCommune + ' (' + commune.value.codeCommune  + ')'">
    </option>
</datalist>

但是:

[label]="commune.value.nomCommune + ' (' + commune.value.codeCommune  + ')'"

让我失望。根据String.Format not work in TypeScript,我可以改用string.format(...)

我试过了,但没有成功(被拒绝):

[label]="'{0} ({1})'.format(commune.value.nomCommune, commune.value.codeCommune)"

在带有 Angular 的 HTML 属性上使用 format(...) 函数的正确方法是什么?

【问题讨论】:

  • 你试过使用 TypeScript 的字符串插值吗?
  • @Bozhinovski :它似乎不起作用。你有这个案例的工作样本吗?
  • 这对我来说看起来是正确的:[label]="commune.value.nomCommune + ' (' + commune.value.codeCommune + ')'"。这是什么管道:键值?您可以尝试删除此管道:“| keyvalue”吗?
  • 它有效,但不符合国际化要求。稍后,页面可能会显示:“Commune : Brest, (29056)”或:“City : Brest (29056)”,具体取决于用户的语言。这就是为什么声明必须更改为textFormat.format(arg1, arg2) 之类的内容。管道键值在这里是因为我正在读取要从 Map 中显示的值。
  • label="{{commune.value.nomCommune}} ({{commune.value.codeCommune}})" 肯定会与 Angular 的原生 i18n 一起使用,如果这是您关心的话。您将能够从翻译文件中将实际显示的文本更改为您想要的任何内容

标签: html angular typescript


【解决方案1】:

你总是可以创建一个函数。例如(*)

format(text: string, ...args: any[]) {
    if (text.match(/\{.\}/))
      text.match(/\{.\}/g).forEach((l,i)=>{
        text=text.replace(l,args[i])
      })
    return text
  }

如果你有,例如

translation={
    en:
    {
      list:'one:{0}, two:{1}'
    },
    es:
    {
      list:'uno:{0}, dos:{1}'
    }
  }
  lang=this.translation.es

你可以有一个 .html 作为

<button (click)="lang=lang==translation.en?
                   translation.es:translation.en">
    click
 </button>
 <p>{{format(lang.list,'hello','word')}}

查看example in stackblitz

(*) 函数替换 in order 参数,所以如果我们写 {0}{1} 或 {1}{0} 甚至 {z}{s}

【讨论】:

    【解决方案2】:

    如果您唯一关心的是以后使用国际化,并且您计划使用 Angular 的原生 i18n,那么这应该可以工作

    label="{{commune.value.nomCommune}} ({{commune.value.codeCommune}})" i18n-label
    

    提取文本后,您可以修改语言翻译文件以显示您想要的任何内容。

    在代码中使用 .format()

    现在,如果您想在字符串上使用.format,您需要按照以下步骤操作:

    步骤 #1 在 *.d.ts 文件中声明方法

    src/mytypes.d.ts

    interface String {
      format(...replacements: string[]): string;
    }
    

    您需要确保您的 tsconfig.app.json 文件已经包含声明文件

    "include": [
      "src/**/*.d.ts"
    ]
    

    步骤 #2 在某处实现方法

    例如,您可以将一些实现(如果来自here)添加到您的 polyfills 文件中

    if (!String.prototype.format) {
      String.prototype.format = function() {
        var args = arguments;
        return this.replace(/{(\d+)}/g, function(match, number) {
          return typeof args[number] != 'undefined'
            ? args[number]
            : match
            ;
        });
      };
    }
    

    之后,您应该可以在 ts 代码和模板文件中使用"mystring".format

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-17
      • 2018-07-26
      • 1970-01-01
      • 2011-04-01
      相关资源
      最近更新 更多