Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 elvis operator and bracket notation / object access by key

So, let's say we got a simple object that holds a string for two different languages like
welcomeText = {"de": "Willkommen zurück!", "en": "Welcome back!"}.

The welcomeText is a property of Texts object that holds all texts and gets delivered asynchronously (so i need to take care of possible undefined values, hence the elvis operator). Now, in my angular2 template i want to show the text based on a current selected language.
This is working (but not what i need):

..
{{Texts?.welcomeText?.de}}   // works, as well as {{Texts?.welcomeText?.en}}
.. 

What i want is this (since language can be changed):

..
{{Texts.?welcomeText?[language]}}
.. 

Unfortunately this results in an error:

EXCEPTION: Template parse errors:
Parser Error: Conditional expression 
      {{Texts?.welcomeText?[language]}}
     requires all 3 expressions at the end of the expression ..

No idea how to fix this error. I'm just not sure if i am using it wrong or if it simply isn't intended to work like that. For the moment i use a simple workaround, but i find it to be somewhat ugly since i have a method call everywhere i want to display text:

..
{{getText('welcomeText')}} 
..
..
getText(name : string){
 if(this.Texts)
   return this.Texts[name][this.language]
..

Is this just the way to go or is there a way to do it the way i want, with the elvis operator?
Thanks a lot for any answers!

like image 790
ch40s Avatar asked Dec 21 '15 18:12

ch40s


1 Answers

you can use it like welcomeText?.[language]

{{ Texts?.welcomeText?.[language] }}
like image 137
kwalski Avatar answered Oct 13 '22 00:10

kwalski