user2175783
user2175783

Reputation: 1441

How to route to child from grandchild

I have the following routes structure (angular 5)

export const ROUTES = [
    { path: "", component: ParentComponent,
        children: [
            { path: "childpath/:param1/:param2/:param3", component: ChildComponent,
                children: [{ path: "grandchildpath", redirectTo: "", pathMatch: "full" },
                    { path: "grandchildpath/:param4/:param5", component: GrandchildComponent }]
            }
        ]
    }
];

when in ChildComponent I call the route "grandchildpath" (no params) I would like to go to "childpath/:param1/:param2/:param3" but instead I get

Error: Cannot match any routes. URL segment: "childpath/:param1/:param2/:param3"

Upvotes: 4

Views: 1316

Answers (1)

Vikas
Vikas

Reputation: 12036

Relative and Absolute Navigation
Navigation can be relative and absolute. Relative navigation replaces a single URL segment with a different one or appends the path you specify in your routerLink to end of the current path.
example: say your current url is localhost:4200/child/1/2/3

<a [routerLink]="['grandchild',4,5]">Go</a>

this would result in currentpath+'/grandchild/4/5' --->localhost:4200/child/1/2/3/grandchild/4/5

 <a [routerLink]="['/grandchild',4,5]">Go</a>

If path starts with a ‘/’, then it is an absolute navigation.

this would result in currentpath+'/grandchild/4/5' --->localhost:4200/grandchild/4/5

Absolute navigation replaces the whole URL.

When you navigate to a route using Router.navigate() method then you need to pass an instance of ActivatedRoute using relativeTo property because navigate() method is unaware of the current route.
When you navigate to a route using RouterLink directive, you need not pass the instance of ActivatedRoute because RouterLink automatically supports ActivatedRoute

Solution 1: use routerLink Directive
In your child.component.html

<a [routerLink]="['grandchild']">Grandchild Without Param</a><br>

Solution 2:
In your child.component.ts

   constructor(private router:Router,private route:ActivatedRoute) { }

      ngOnInit() {
      }

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

Live Demo

Upvotes: 2

Related Questions