Home > Net >  Pass data to children component in angular
Pass data to children component in angular

Time:11-04

I am using angular and I have two children components and I wanna pass data to them. Here is how I wrote my code: This is the home template

<div >
    <mat-card style="width: 500px;">
      <mat-card-title style="display: flex; align-items: center; justify-content:space-between">
        <span>Employees</span>
        <button mat-raised-button color="primary" routerLink="/home/add-employee">Add</button>
      </mat-card-title>
      <router-outlet ></router-outlet>
    </mat-card>
  </div>

Then on the <router-outlet></router-outlet> that's where the children components show. I know how to pass data to child if I included only one child component like <app-child [data]="data"></app-child> in place of <router-outlet></router-outlet> on the code above. So I wanna know how can I achieve this the way I want

CodePudding user response:

You have three options to pass data to components injected by angular's router. You can pick what you want according to your needs:

1. You want to pass static data to the child (only depending on the route)

In order to achieve this, you can just pass the data property to your route config, which can then be retrieved by your child component via ActivatedRoute.data

2. You want to pass data from the parent component (the one including the router-outlet) to a child injected by Angular router

This can be achieved by setting the state property (available from Angular 7.2.0 on) in your navigate call like

this.router.navigate(['your-child-route'], { state: 'your-data' });.

You can then read it in your child component by using

this.router.getCurrentNavigation().extras.state.

If you are navigating by using routerLink in your template, you can pass the state as a property: [state]="'your-data'"

3. Use a service to receive and propagate the values.

You can also use a service, which can receive data, write it to a Subject and then use the child component to subscribe to this subject.

CodePudding user response:

Parent Component Html

<div >
    <mat-card style="width: 500px;">
      <mat-card-title style="display: flex; align-items: center; justify-content:space-between">
        <span>Employees</span>
        <button mat-raised-button color="primary" routerLink="/home/add-employee">Add</button>
      </mat-card-title>
      <app-child1 [data]="data" ></app-child1>
    </mat-card>
  </div>

Parent Component ts file

data:any=[]; // any data that you want to pass from parent.

Child component ts file

@Input() data: any = [];
  • Related