Search code examples
htmlangularinterpolationtranslatengx-translate

Angular Translate: Using .replace in an interpolation string in HTML


I am trying to combine interpolation and angular-translate to retrieve lang translations from en -> fr from a couple json files. All the definitions are defined however to display the interpolated string in HTML it looks like this:

{{ 'this.section.in.json.' + object.param | translate}}

so it'll take the param as a string, find it in the en.json and if the setting is french find the translation in fr.json. My issue is that Object.param is coming from an API and it has a whitespace in it while the json is structured differently:

Need param with no spaces--> "thisString": "this String" <--Object.Param returns this

I can define a function in my component to use .replace() and return a new value but there's a lot of different translations to deal with for a lot of different params. Is there a way to use .replace in the interpolation string in the html file? as shown below

{{ 'this.section.in.json.' + object.param.replace(*regex*, '') | translate}}

Solution

  • I would just make a new pipe that strips out white spaces. Just be sure to register it in your app module.

    import { Component, Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({ name: 'stripSpaces' })
    export class StripSpaces implements PipeTransform {
      transform(str: string): any {
        return str.replace(/\s/g, '')
      }
    }
    

    Then in your template use this

      {{ 'this.section.in.json.' + object.param | stripSpaces | translate }}