Lightning: why can you not have an expression combined with text in an HTML attribute?

So, I’ve been struggling with this for a while, trying to figure out how to get it to work. Here is what I originally did:

<button class="btn btn-primary {!v.isLink1 ? 'active' : ''}">

And so on. Here’s the documentation on it. Example Expressions

However, when you actually try to save this in the developer console, you get the error:

Field Integrity Exception: Failed to save undefined: Cannot mix expression and literal string in attribute value, try rewriting like {!'foo' + v.bar}: Source

I finally figured out that you have to put all of the classes inside of the expression, like so:

<button class="{!v.isLink1 ? 'btn btn-primary active' : 'btn btn-primary'}">

This doesn’t seem very intuitive. It’s also not documented anywhere I could find. Could someone explain to me why it is this way and if it will ever change?

(and hopefully this question saves someone some headaches in the future)

Answer

It works this way

<button class="{! 'btn btn-primary' + ' ' +  (v.isLink1 ? 'active' : ' ' )}">

OR

<button class="{! 'btn btn-primary' + ' ' +  if(v.isLink1,'active','')}">

the whole attribute value has to be within an expression “{! …}”
Note that the strings have been concatenated with a + sign.

Attribution
Source : Link , Question Author : Anthony F. , Answer Author : Vamsi Krishna Gosu

Leave a Comment