Search code examples
javascripthtmlangularangular-router

Passing data via a routerLink angular router template expression?


Playing around with the stackblitz starting point and I added the following routing:

    const routes : Routes = [ {path: 'hello', 'component': HelloComponent}];


    @NgModule({
      imports:      [ 
        RouterModule.forRoot(routes, {enableTracing: true}) ],
      declarations: [ AppComponent, HelloComponent ],
    })

Also added a <router-outlet> to the app-component.html template, and the hello-component is rendered when the below link is clicked:

<a routerLink="hello" routerLinkActive="active">hello</a>

However the property on the hello-component component is empty when the link is clicked:

@Input() name: string;

Is there a way to pass in a value via a template expression such that the name property is set on the component and is evaluated in the hello-component.ts's template string with the hello anchor is clicked?

Just for reference the hello component looks like this:

    import { Component, Input } from '@angular/core';

    @Component({
      selector: 'hello',
      template: `<h1>Hello {{name}}!</h1>`,
      styles: [`h1 { font-family: Lato; }`]
    })
    export class HelloComponent  {
      @Input() name: string;
    }

It seems like perhaps an ActivatedRoute instance has to be examined for for a property for this to work?


Solution

  • Firstly, amend your route definition to allow a path parameter, like so:

    const routes : Routes = [ 
      {path: 'crisis-center', 'component': HelloComponent}, 
      {path: 'hello/:name', 'component': HelloComponent}, 
      {path: '**', 'component': HelloComponent}
    ];
    

    This will allow you to pass a name parameter to the /hello route.

    To access it within the component, you need to subscribe to the paramter changes, like so:

    export class HelloComponent  {
      @Input() name: string;
    
      constructor(private route: ActivatedRoute) {
    
      }
    
      ngOnInit(){
        this.route.paramMap.subscribe( params =>
            this.name = params.get('name')
        )
      }
    }
    

    And finally, you can then pass a value in via the routerLink, like so:

    <a [routerLink]="['hello', routeOneName]" routerLinkActive="active">hello</a>
    

    Where routeOneName is a variable declared in AppComponent.

    I've created a fork of your StackBlitz here if you'd like to look