如何在没有 ngx-translate-messageformat-compiler 插件的情况下在 ngx-translate 中使用复数

问题描述 投票:0回答:2

我在使用 ngx-translate-messageformat-compiler 插件时遇到问题(添加复数形式后 json 文件解析失败)。 ¿还有其他选择吗?

angular angular8 ngx-translate
2个回答
11
投票

我决定实现一个自定义管道:

管道

@Pipe({
  name: 'pluralTranslate',
  pure: false
})
export class PluralTranslatePipe implements PipeTransform {

  transform(key: string, number: number): string {

    return `${key}.${number == 0 ? 'none' : number == 1 ? 'singular' : 'plural'}`;
  }
}

使用

{{ 'daysNumber' | pluralTranslate:2 | translate:{ days: 2} }}

留言

{
"daysNumber": {
      "none": "",
      "singular": "{{ days }} day",
      "plural": "{{ days }} days"
    },
}

0
投票

这是我的定制管道:

import { ChangeDetectorRef, Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Pipe({
    name: 'pluralTranslate',
    pure: false
})
export class PluralTranslatePipe implements PipeTransform {
    private _value: string;

    private suffixes = ['none', 'one', 'few', 'many', 'other'];

    constructor(
        private translateService: TranslateService,
        private _ref: ChangeDetectorRef
    ) {}

    transform(key: string, args: { count: number }): string {
        if (!this._value) {
            const keys = [key, ...this.suffixes.map((s) => key + '_' + s)];
            this.translateService.get(keys, args).subscribe((res) => {
                if (res[key] !== key) {
                    // fallback when no translation is found
                    this._value = res[key];
                } else {
                    let val: string;
                    if (typeof args.count !== 'number' || args.count === 0) {
                        val = res[key + '_' + this.suffixes[0]];
                    } else if (args.count === 1) {
                        val = res[key + '_' + this.suffixes[1]];
                    } else if (args.count > 1 && args.count < 5) {
                        val = res[key + '_' + this.suffixes[2]];
                    } else if (args.count >= 5) {
                        val = res[key + '_' + this.suffixes[3]];
                    }

                    if (!val || val.startsWith(key + '_')) {
                        val = res[key + '_' + this.suffixes[4]];
                    }

                    this._value = val;
                }

                this._ref.markForCheck();
            });
        }

        return this._value;
    }
}

用途:

'viewsCount' | pluralTranslate: { count: 25 }

翻译文件:

"viewsCount_one": "{{count}} zhlédnutí",
"viewsCount_other": "{{count}} zhlédnutí",
"viewsCount_few": "{{count}} zhlédnutí",
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.