0

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}}
1
  • yes you can use the Javascript function but not Global JavaScript variable functions like window, document etc. Commented Sep 15, 2018 at 9:32

2 Answers 2

2

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 }}
Sign up to request clarification or add additional context in comments.

1 Comment

Both answers work well but this one is more complete. Regardless, Thank you both~
1

Nope, you can't use those method-functions directly in the interpolation context. But you can chain pipes. Which means that you can write your own pipe for removing those whitespaces at first and then have your translation applied afterwards.

e.g.:

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

Here you first remove whitespaces and then the 'cleaned' string gets translated.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.