Jacopo Sciampi
Jacopo Sciampi

Reputation: 3433

Lazy loaded route works with routerLink but doesn't with router.navigate

I have a very simple main route defined as follow:

path: 'something',
loadChildren: () => import('./foo.module').then(m => m.FooModule)

the lazy loaded module has its own route defined:

path: '',
component: FooComponent,
children: [
  {
    path: 'edit',
    component: SecondComponent
  }
]

in the Foo.component.html I have a button defined as

<button  [routerLink]="'edit'">My Button</button>

And whenever I clicked the button it navigates correctly to the page of SecondComponent.

But if I change that to

<button (click)="tryToNavigate()">My Button</button>

public tryToNavigate(): void {
  this._router.navigate(['edit']);
}

it says that it cannot match any route 'edit'.

I've also tried using /edit both on the function and the route definition with no success.

What am I doing wrong?

Upvotes: 1

Views: 1500

Answers (4)

Chris Gajete
Chris Gajete

Reputation: 1

I've had a similar problem, which I circumvented by breaking the navigation in two steps, which here would be like:

this._router.navigate(['something']).then(() => {
      this._router.navigate(['edit'])
});

The first navigation triggers the module loading, so the second navigation can proceed to target.

Upvotes: 0

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

The reason why it worked when you use routerLink because it uses relativeTo implicitly, but when you use navigate method you need to provide it so that angular can navigate to the correct router.

So, when you only use navigate without relativeTo, it tries to navigate to path edit which is not defined at root but in the child route.

constructor(private route: ActivatedRoute) { }

public tryToNavigate(): void {
  this._router.navigate(['edit'], {relativeTo: this.route}); // make it work similar to routerLink
}

Upvotes: 0

S Overfow
S Overfow

Reputation: 161

You can explicitly set relative route:

constructor(private route: ActivatedRoute) { }

public tryToNavigate(): void {
  this._router.navigate(['edit'], {relativeTo: this.route});
}

Upvotes: 2

Ali Celebi
Ali Celebi

Reputation: 1008

I wonder if you put a slash in front of edit, would it work? Like this this._router.navigate(['/edit']); If not, can you demonstrate the issue on Stackblitz?

Upvotes: 0

Related Questions