Uli Köhler
Uli Köhler

Reputation: 13750

Angular2 route-link from child component has no effect

When I was experimenting with Angular2's router (2.0 beta 6), I encountered an issue regarding a routeLink (or router.navigate) being called from a child component.

My main component looks like this:

@Component({
  selector: 'myapp',
  template:`
  <div>
    <alink></alink>
    <router-outlet></router-outlet>
  </div>
  `,
  directives: [ROUTER_DIRECTIVES, ALinkComponent],
  providers: [ROUTER_PROVIDERS]
})
@RouteConfig([
    {
      path: '/first',
      name: 'First',
      component: FirstComponent,
      useAsDefault: true
    },
    {
      path: '/second',
      name: 'Second',
      component: SecondComponent
    }
])
export class MyApp {
}

<alink> simply shows a link with a [routerLink] to Second:

@Component({
  selector: 'alink',
  template: `<h3><a [routerLink]="['Second']">Should redirect to second</a></h3>`,
  directives: [ROUTER_DIRECTIVES],
  providers: [ROUTER_PROVIDERS]
})
export class ALinkComponent {
}

However, when clicking on this link, nothing happens (not even a message pops up on the console). A link from the MyApp template works perfectly find. Using a (click)=... handler with router.navigate(...) also doesn't work.

What do I need to change in order to make the routerLink work in any nested component?

A full example is available on Plunker

Upvotes: 1

Views: 1737

Answers (2)

Uli K&#246;hler
Uli K&#246;hler

Reputation: 13750

Based on @MattScarpino's answer very helpful answer and this blogpost I was able to figure out a more simple way of doing this without injecting MyApp directly:

@Component({
  selector: 'alink',
  template: `<h3><a (click)="viewSecond()">Should redirect to second but does not</a></h3>`,
  directives: [ROUTER_DIRECTIVES],
  providers: [ROUTER_PROVIDERS]
})
export class ALinkComponent {
  constructor(injector: Injector) {
    this.router = injector.parent.get(Router);
  }

  viewSecond() {
    this.router.navigate(["Second"])
  }
}

The disadvantage of this solution is likely that we might need to use parent or parent.parent depending on the circumstances. However, we avoid explicit references to the toplevel component.

Upvotes: 1

MatthewScarpino
MatthewScarpino

Reputation: 5936

I got your example working here, but I had to add a fair amount of code. The problem is that ALinkComponent doesn't have a RouteConfig of its own, so it needs to access MyApp's router and call its navigate method.

Upvotes: 1

Related Questions