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

Time:09-23

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

CodePudding user response:

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.

CodePudding user response:

Using Router.navigate And NavigationExtras

In .ts file

import { NavigationExtras, Router } from '@angular/router';

constructor(private router: Router) {}

 navigate() {
    const someId = 1;
    if (someVariable) {
      let navigationExtra: NavigationExtras = {
        queryParams: { someParam: 'x', origin: 'origin' },
        fragment: 'anchor',
      };

      this.router.navigate([`/somelink/${someId}`], navigationExtra);
    }
  }

In template:

<a (click)="navigate()">Go to ...</a>
  • Related