Search code examples
angularangular-routing

Pass variable to Angular routerLink


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.


Solution

  • 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);
                         }
              }
    
          );
      }
    }