Angular : How to pass data from parent to child for children added through router

Angular : How to pass data from parent to child for children added through router

In Angular, when passing data from a parent component to a child component that is added through the router (i.e., routed components), you typically use route parameters or query parameters to achieve this. Here's how you can pass data from a parent component to a child component that is added through the router:

Using Route Parameters

  1. Define Route with Parameter

    In your routing module (app-routing.module.ts), define a route with a parameter:

    import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { ChildComponent } from './child.component'; const routes: Routes = [ { path: 'child/:id', component: ChildComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } 

    Here, :id is a route parameter that can be passed from the parent component.

  2. Parent Component Navigation

    Navigate to the child component (ChildComponent) from the parent component and pass data using Router:

    import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-parent', template: ` <button (click)="navigateToChild()">Go to Child</button> ` }) export class ParentComponent implements OnInit { constructor(private router: Router) { } ngOnInit() { } navigateToChild() { let id = 123; // Example data to pass this.router.navigate(['/child', id]); } } 
  3. Child Component (Receive Data)

    In the child component (ChildComponent), retrieve the parameter using ActivatedRoute:

    import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-child', template: ` <p>Received ID: {{ id }}</p> ` }) export class ChildComponent implements OnInit { id: number; constructor(private route: ActivatedRoute) { } ngOnInit() { // Subscribe to route params to get the ID this.route.params.subscribe(params => { this.id = +params['id']; // (+) converts string 'id' to a number }); } } 

Using Query Parameters

Alternatively, you can pass data as query parameters:

  1. Define Route with Query Parameters

    Modify the route definition to use query parameters:

    const routes: Routes = [ { path: 'child', component: ChildComponent } ]; 
  2. Parent Component Navigation

    Navigate to the child component and pass data using Router with query parameters:

    navigateToChild() { let id = 123; // Example data to pass this.router.navigate(['/child'], { queryParams: { id: id } }); } 
  3. Child Component (Receive Data)

    In the child component, retrieve the query parameter using ActivatedRoute:

    ngOnInit() { this.route.queryParams.subscribe(params => { this.id = +params['id']; }); } 

Summary

  • Route Parameters: Used for passing data through the route path (/child/:id).
  • Query Parameters: Used for passing data as key-value pairs in the URL (/child?id=123).

Choose the method (route parameters or query parameters) based on your application's requirements for passing data from a parent component to a child component added through the Angular router.

Examples

  1. How to pass data from parent component to child component in Angular using @Input() for routed components?

    • Description: Learn how to pass data from a parent component to a child component that is loaded via Angular router using @Input() decorators.
    • Solution: Use @Input() decorators in the child component to receive data passed from the parent component via router navigation or router outlets.
    // parent.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-parent', template: ` <router-outlet [childData]="parentData"></router-outlet> ` }) export class ParentComponent { parentData = 'Data from parent'; } 
    // child.component.ts import { Component, Input } from '@angular/core'; @Component({ selector: 'app-child', template: ` <div>{{ childData }}</div> ` }) export class ChildComponent { @Input() childData: string; } 
  2. How to pass data using route parameters from parent to child components in Angular?

    • Description: Pass data via route parameters when navigating to child components through Angular router configuration.
    • Solution: Extract route parameters in the child component using ActivatedRoute and subscribe to paramMap changes to fetch data from the parent.
    // parent.component.html <a [routerLink]="['/child', { id: 1 }]">Go to Child Component</a> 
    // child.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, ParamMap } from '@angular/router'; import { switchMap } from 'rxjs/operators'; @Component({ selector: 'app-child', template: ` <div>{{ childData }}</div> ` }) export class ChildComponent implements OnInit { childData: string; constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.paramMap.pipe( switchMap((params: ParamMap) => { this.childData = params.get('id'); return this.service.getData(this.childData); }) ).subscribe(data => { // Process data here }); } } 
  3. How to use Angular services to pass data between parent and child components loaded via router?

    • Description: Utilize Angular services as a mediator to pass data between parent and child components instantiated through Angular router.
    • Solution: Inject the service into both the parent and child components to set and retrieve shared data.
    // shared.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class SharedService { data: any; setData(data: any) { this.data = data; } getData() { return this.data; } } 
    // parent.component.ts import { Component } from '@angular/core'; import { SharedService } from '../shared.service'; @Component({ selector: 'app-parent', template: ` <button (click)="passData()">Pass Data to Child</button> <router-outlet></router-outlet> ` }) export class ParentComponent { constructor(private sharedService: SharedService) {} passData() { this.sharedService.setData('Data from parent'); } } 
    // child.component.ts import { Component, OnInit } from '@angular/core'; import { SharedService } from '../shared.service'; @Component({ selector: 'app-child', template: ` <div>{{ sharedService.getData() }}</div> ` }) export class ChildComponent implements OnInit { constructor(public sharedService: SharedService) {} ngOnInit() {} } 
  4. How to pass data using state management libraries like NgRx between parent and child components in Angular routed scenarios?

    • Description: Implement data sharing using NgRx state management between parent and child components loaded through Angular router.
    • Solution: Define actions, reducers, and selectors in NgRx store to manage state and pass data between components.
    // app.state.ts import { createFeatureSelector, createSelector } from '@ngrx/store'; export interface AppState { data: string; } export const selectData = (state: AppState) => state.data; export const getData = createSelector( selectData, data => data ); 
    // parent.component.ts import { Component } from '@angular/core'; import { Store } from '@ngrx/store'; import { AppState } from '../app.state'; @Component({ selector: 'app-parent', template: ` <button (click)="passData()">Pass Data to Child</button> <router-outlet></router-outlet> ` }) export class ParentComponent { constructor(private store: Store<AppState>) {} passData() { this.store.dispatch({ type: 'SET_DATA', payload: 'Data from parent' }); } } 
    // child.component.ts import { Component, OnInit } from '@angular/core'; import { Store, select } from '@ngrx/store'; import { AppState, getData } from '../app.state'; import { Observable } from 'rxjs'; @Component({ selector: 'app-child', template: ` <div>{{ data$ | async }}</div> ` }) export class ChildComponent implements OnInit { data$: Observable<string>; constructor(private store: Store<AppState>) {} ngOnInit() { this.data$ = this.store.pipe(select(getData)); } } 
  5. How to use BehaviorSubject to pass data between parent and child components in Angular?

    • Description: Implement a BehaviorSubject to facilitate data communication between parent and child components loaded via Angular router.
    • Solution: Define a service with a BehaviorSubject to store and retrieve data, and subscribe to changes in both parent and child components.
    // data.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root', }) export class DataService { private dataSource = new BehaviorSubject<string>('Initial data'); currentData = this.dataSource.asObservable(); changeData(data: string) { this.dataSource.next(data); } } 
    // parent.component.ts import { Component } from '@angular/core'; import { DataService } from '../data.service'; @Component({ selector: 'app-parent', template: ` <button (click)="passData()">Pass Data to Child</button> <router-outlet></router-outlet> ` }) export class ParentComponent { constructor(private dataService: DataService) {} passData() { this.dataService.changeData('Data from parent'); } } 
    // child.component.ts import { Component, OnInit } from '@angular/core'; import { DataService } from '../data.service'; @Component({ selector: 'app-child', template: ` <div>{{ data }}</div> ` }) export class ChildComponent implements OnInit { data: string; constructor(private dataService: DataService) {} ngOnInit() { this.dataService.currentData.subscribe(data => this.data = data); } } 
  6. How to pass complex objects or arrays from parent to child components in Angular routed scenarios?

    • Description: Transmit and handle complex data structures such as objects or arrays between parent and child components instantiated via Angular router.
    • Solution: Use @Input() decorators in child components to receive and process complex data structures passed from parent components.
    // parent.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-parent', template: ` <router-outlet [childData]="parentData"></router-outlet> ` }) export class ParentComponent { parentData = { name: 'John', age: 30, city: 'New York' }; } 
    // child.component.ts import { Component, Input } from '@angular/core'; @Component({ selector: 'app-child', template: ` <div>{{ childData.name }}, {{ childData.age }}, {{ childData.city }}</div> ` }) export class ChildComponent { @Input() childData: any; } 

More Tags

asp.net-mvc-5.1 amazon-elb jmx simplexml uislider sse delete-row opencv buildpath android-external-storage

More Programming Questions

More Biochemistry Calculators

More Internet Calculators

More Physical chemistry Calculators

More Dog Calculators