Search code examples
angularhrefconditional-operator

Conditional url with ternary operator in anchor tag href throws Parse Error Angular


Good day developers. I´m trying to set dynamically a URL for my anchor tag href in a html template but I´m receiving this error:

Parser Error: Got interpolation ({{}}) where expression was expected at column 30 in 
[somevariable?['/somelink/{{ some.id }}?someparam={{ paramid }}&origin=origin']:'']

the href would be redirecting to an URL if some random variable of boolean type has a true value, thus:

 <a [href]="(somevariable)?('/somelink/{{ some.id }}?someparam={{ paramid }}&origin=origin'):''">
 </a>         
        

is there a better approach for this?...thanks in advance


Solution

  • You can change your interpolation to this:

    <a href="{{ somevariable ? '/somelink/' + some.id + '?someparam=' + paramid + '&origin=origin' : '' }}">
    

    But your anchor tag could end up without a link if somevariable is false. So I would suggest you instead hide the anchor tag in that instance using *ngIf:

    <a *ngIf="somevariable" href="{{ '/somelink/' + some.id + '?someparam=' + paramid + '&origin=origin' }}">
    
    

    Additionally, I would suggest you use routerLink instead href if /somelink/... is a route in your app so your app does not reload when the user follows (clicks on) the link.