Search code examples
javascriptangularangular-routing

Navigate programmatically with relativeTo a nested route result in "Error: Cannot match any routes."


My router looks like Full example here in StackBlitz:

const eventChildren = [    
    { path: 'new', component: FooEditComponent }    
];

const appRoutes : Routes = [
    { path: '', redirectTo: '/foos' , pathMatch: 'full'},
    { path: 'foos/:year/:month/:day', component: FoosComponent, children: eventChildren}
]

When the user navigate from the URL bar by pasting this address in the URL bar: https://angular-tfty2q.stackblitz.io/foos/2020/4/20/new everything works as expected (The FooEditComponent child component is being rendered as expected).

But when the user first navigate to https://angular-tfty2q.stackblitz.io/foos/2020/4/20/, and then try to navigate to the same "New" route address (programmatically) from the HeaderComponent (parent) by clicking the "New" li with:

header.component.html:

<ul>
  <li style="cursor: pointer;"><a (click)="onNewClick()">New</a></li>
</ul>

header.component.ts:

onNewClick() {
    this.router.navigate(['new'], {relativeTo: this.route});
}

It resulted in error:

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'new'

I already tried various similar answers like (1,2,3) with no progress.


Solution

  • You can move the li to foos.component.html

    <ul>
        <li style="cursor: pointer;"><a [routerLink]="['./new']">New</a></li>
    </ul>
    

    Working Demo