Andrew Howard
Andrew Howard

Reputation: 3072

Get param from parent component to child component

There have been so many alterations to the Angular router as of late I don't know how to go about this.

I have a param on my parent component called "eventId" which is in the address bar:

http://localhost:4200/event/1

In this case it's value is 1.

Here's how I declare it in the routing component:

{ path: 'event/:eventId', loadChildren: './event/event.module#EventModule', canActivate: [AuthGuard] },

So I have a child component which is way down the line:

http://localhost:4200/event/1/event-travel-agents/purchase-plans

On my purchase plans component, how can I get the eventId?

I've tried:

import { ActivatedRoute } from '@angular/router';
export class PurchasePlansComponent implements OnInit {
  eventId: number;
  constructor(private activatedRoute: ActivatedRoute) {
    this.subscription = activatedRoute.parent.params.subscribe(
      (param: any) => {
        this.eventId = param['eventId'];
      }
    );
  }
  ngOnInit() {
    alert(this.eventId);
  }
}

But this only works if I'm at this level:

http://localhost:4200/event/1/event-home

But if I'm at this level it won't work:

http://localhost:4200/event/1/event-travel-agents/purchase-plans

Upvotes: 2

Views: 1560

Answers (2)

Borad Akash
Borad Akash

Reputation: 804

In Angular 5.2 release there is new feature of paramsInheritanceStrategy ,that can help you for your problems now.

You can use it as following

@NgModule({
    import :[RouterModule.forRoot(router,{paramsInheritanceStrategy :'always'})]
})

It defines how the router merges params, data and resolved data from parent to child

Available options are:

1. emptyOnly: the default , only inherits parent params for path-less or component-less

2. always: enables unconditional inheritance of parent params.

In component you can use it as follows:

 constructor(private route: ActivatedRoute) {}

 ngOnInit() {
    this.eventId = +this.route.snapshot.paramMap.get("eventId");
  }

Upvotes: 3

Andrew Howard
Andrew Howard

Reputation: 3072

Thanks for all your help. The answer was very lengthy. Without subscription the line was:

this.eventId = this.activatedRoute.parent.snapshot.parent.params.eventId;

Upvotes: 0

Related Questions