Get param from parent component to child component

感情迁移 提交于 2019-12-07 20:40:55

问题


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

回答1:


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");
  }



回答2:


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

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


来源:https://stackoverflow.com/questions/46935269/get-param-from-parent-component-to-child-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!