0

My current URL:

http://localhost:4200/app/projects/ABC1/dashboards/5f6cc1e632acae2b16160123

What I want to do is that when I click on a button, that the URL gets changed to http://localhost:4200/app/projects/ABC1/dashboards/new

I am trying it with routerLink

<button [routerLink]="['./projects/' + projectId + '/dashboards/new']">

but how can I replace projectId with the variable that I have in that place?

I also tried to pass a function to routerLink which returns the following

public routeToCreateDashboard = (projectId: string): string => {
    return `./projects/${projectId}/dashboards/new`;
  };

but this doesnt work too.

mrks
  • 5,439
  • 11
  • 52
  • 74
  • Does this answer your question? [Angular variable into routerLink](https://stackoverflow.com/questions/53523472/angular-variable-into-routerlink) – Roy Jan 26 '21 at 13:58
  • @Roy Unfortunately not because I need to have the variable in my URL and not passed as param. – mrks Jan 26 '21 at 14:03
  • 1
    Can you reproduce this in a [stackblitz](https://www.stackblitz.com)? I don't see the problem here. And yes, you can absolutely have a `(click)` and `routerLink` on the same element. –  Jan 26 '21 at 14:09

1 Answers1

1

For String Interpolation this might help you:

// You can use String Interpolation this way

routerLink="/update/{{obj.id}}"

for add event when route changed you can use router event:

import {Injectable} from '@angular/core';
import {NavigationEnd, Router, RouterEvent} from '@angular/router';
import {filter, map} from 'rxjs/operators';
import {Observable} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RouteEventService {
  constructor(private router: Router) {
  }

  subscribeToRouterEventUrl(): Observable<string> {
    return this.router.events
      .subscribe(  (event: RouterEvent) => {
                     if(event instanceof NavigationStart){

                     // console.log('Navigation Start', this.router.url);
                     }
          }

      );
  }
}
Masoud Bimmar
  • 6,941
  • 4
  • 30
  • 33