ngx-translate / core

The internationalization (i18n) library for Angular
MIT License
4.51k stars 574 forks source link

Support expressions (at least simple ternaries) #1131

Open hoeni opened 5 years ago

hoeni commented 5 years ago

Current behavior

Currently, a translation can only directly output a placeholder expression without further manipulation.

Expected behavior

It would be nice to be able to use expressions like "{{ n === 0 ? 'No' : n}} item{{ n ===1 ? '' : 's'}}" Example: https://stackblitz.com/edit/angular-4q9app

What is the motivation / use case for changing the behavior?

It's a common use case to vary string depending on the number. This is supported by AngularJS/ng-translate, as well as angular-translate.

How do you think that we should implement this?

Best would be, of course, not to focus on ternary expressions only, but simply allow any meaningful parseable expression, e.g. in JS. However, these ternaries make up the most use cases (at least in our apps :-) ).

aliriomendes commented 3 years ago

+1

koiralakiran1 commented 2 years ago

+1

Does anyone have a workaround for this for the time being?

koiralakiran1 commented 2 years ago

Found a workaround. This library (ngx-interpolation) seems to work for some additional interpolation cases, at least for Angular 9, as mentioned in it's readme. I haven't tried it with other versions though but it should work. I created a custom parser with it and overwrote the ngx-translate's default parser.

import { Injectable } from '@angular/core';
import { NgxInterpolation } from 'ngx-interpolation';
import { TranslateDefaultParser } from '@ngx-translate/core';

@Injectable()
export class NgxTranslateParser extends TranslateDefaultParser {

    constructor(
        private NgxInterpolation: NgxInterpolation
    ) {
        super();
    }

    public interpolate(expr: string | Function, params?: any): string {
        if (!params || typeof expr === 'function') {
            return super.interpolate(expr, params);
        }

        return this.NgxInterpolation.interpolate(expr, params);
    }
}

And while importing the TranslateModule, provide your custom parser.

@NgModule({
    imports: [
        TranslateModule.forRoot({
            parser: {
                provide: TranslateParser,
                useClass: NgxTranslateParser,
            },
        }),
    ],
})
export class AppModule {}