rainbowrider
rainbowrider

Reputation: 7

Conditional data binding in Angular with piped (translate) variables

Hey stackoverflow / Angular Community!

I have a little question about data-binding on components. The [value] on my component can have two different strings/labels as value. Since the app knows more languages I am using the translate-pipe for this. The code-excerpt is probably very self-explanatory.

<my-component [value]="bool1 ? {{'GLOBAL.YES' | translate }} : {{'GLOBAL.NO' | translate }}"></my-component>

Leads to: Uncaught Error: Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected

It feels like there is a syntax thing, I am missing out on. Tried a lot of different combinations. When I try value without the brackets I end up having the whole string starting with 'bool1 ? ...' as value (what definetly makes sense).

Maybe someone knows how to fix this?

Thank you all in advance.

Upvotes: 0

Views: 3256

Answers (3)

saumil_
saumil_

Reputation: 323

You can use as following way

<component [value]="(bool1 ? 'GLOBAL.YES' : 'GLOBAL.NO') | translate"></component>

Upvotes: 0

Arminas Šaltenis
Arminas Šaltenis

Reputation: 176

You can't do interpolation in property binding. You can use a method that JFPicard showed.

Or, if you really need to do this in template, do this:

<my-component [value]="(bool1 ? 'GLOBAL.YES' : 'GLOBAL.NO') | translate"></my-component>

Upvotes: 2

JFPicard
JFPicard

Reputation: 5168

If you're using ngx-translate, you can probably do it in the .ts like this:

<my-component [value]="getTranslation(bool1)" />

And in your ts

  private getTranslation(value: boolean): string {  
    return value ? translate.instant("GLOBAL.YES"): translate.instant("GLOBAL.NO")
  }

Upvotes: 0

Related Questions