How to navigate to a parent route from a child route? - GeeksforGeeks

12 Nov, 2020
In angular, a root component that serves as the parent component of all the components and rest of the other components can be called a Child Component to the root component. This structure is in a form of a tree where a component which is the parent of a child lies above the child component and this there is no direct link between them but in general, a parent component can be routed from the child component via two ways:
Directly using the routerLink directive in case of linkage of child to parent.Using Route class in case of navigation to happen on a triggered event.
Directly using the routerLink directive in case of linkage of child to parent.
Using Route class in case of navigation to happen on a triggered event.
Approach: 
Before performing the above two operations, there is a need to register this component in the Route class’s instance which lies inside the app-routing.module.ts file. This will be further used to navigate from child to parent.
The routing should be defined within the app-routing.module.ts file as follows:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ParentComponent } from './parent/parent.component';
import { ChildComponent } from './parent/child/child.component';


const routes: Routes = [
  {path: 'parent' , component: ParentComponent},
  {path: 'parent/child' , component: ChildComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Once it is done, anyone of the two methods can be used to route to parent from a child.Syntax:  
To register routes in angular for any component, set the path and the class name of the component inside the app-routing.module.ts file. The syntax for the same is given as follows: 
import { Routes, RouterModule } from '@angular/router';
import { Component_1 } from 'path_to_component_1';
import { Component_2 } from 'path_to_component_2';

const routes: Routes = [
  {path: 'URL_mapping_component_1' , component: Component_1},
  {path: 'URL_mapping_component_2' , component: Component_2}
];

As components are different from web pages and thus are to be registered with proper URL paths, which will map the respective path to the respective component.
Basic Examples and Explanations 
Using routerLink directive: 
This is a simplest method that can be used to redirect to any component allover the project. It is used within the template as a option acting equivalent to the href option in in the anchor tag, the difference is that, that it links a anchor to the components within the angular project.
It is used as a directive within the anchor tag. The child template file code is given as follows:
html
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport"          content="width=device-width,                   initial-scale=1.0">    <title>Document</title></head><body>          <a [routerLink]=     "[ '/parent']" [queryParams]="{GfG: 'Geeks for Geeks'}">               Redirect message to parent      </a></body></html>
The routerLink is set to the parent component route. Just to add up, queryParams directive is used to send a message to the parent component via the query string.
In the parent component file the query parameter can be accessed as follows:
@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
  constructor( private activateRoute: ActivatedRoute) {
   }
   message = this.activateRoute.snapshot.queryParamMap.get('GfG')
  ngOnInit() {
 
  }
  
}

Within the message variable the parameter is received and the message s stored. It captures using the ActivatedRoute class.
html
<!DOCTYPE html><html>    <head>      <title>Page Title</title>    </head><body> <p>On the Parent page </p>  <p>    Message By Child is {{message}}</p> </body></html>
Using the Route.navigate() method: 
In this we will be using the Route class from @angular/route module. The route object is used to route to the page dynamically via component part of the .ts file. This object has a .navigate() method to route to different modules. It takes two parameters, first is the routing path, and 2nd is the object consisting of information about the query parameters to send, relativity to the path for route etc. This method is used when there is a need to conditionally trigger an event via template.
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

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

  ngOnInit(){}
  redirect_to_parent(){  
  this.router.navigate(["../../parent"], {
  relativeTo: this.activatedRoute, queryParams: 
        {GfG: 'Geeks for Geeks'}});
} 
}


The code above is for the child’s component file, within which a method redirect_to_parent() is triggered using a button in the template to perform the action of redirection and send a message to the parent component. The template file for the child is given as follows:
html
<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport"          content="width=device-width,                   initial-scale=1.0">    <title>Document</title></head><body>          <button (click)="redirect_to_parent()">         Click to redirect      </button></body></html>
Output: 
  
 
bunnyram19
AngularJS-Misc
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Auth Guards in Angular 9/10/11
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
How to set focus on input field automatically on page load in AngularJS ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?