Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subscribe to child route changes in master/detail example in Angular 2

I have a problem with routing in a master/detail view. If i go to the route /master the InfoComponent should show some general info. And if I go to /master/1 the DetailsComponent should show some data for the item with id 1. In both cases, MasterComponent should show either the selected id or nothing.

I can get this working fairly well. But the problem is that I want to subscribe to the selected :id in OnInit in MasterComponent so that I can highlight it there, something like this:

this.selectedId = this.route.params.map((params: Params) => params["id"])

But that doesn't work since :id is a child route param. And I can't use this.route.firstChild since firstChild will be another route depending on if InfoComponent or DetailsComponent is showing.

Can I get an observable (of :id) that changes when MasterComponent changes between showing the two child components?

This is my routing module:

@NgModule({
    imports: [
        RouterModule.forChild([
            {
                path: "master",
                canActivate: [AuthenticationGuardService],
                children: [
                    {
                        path: "",
                        component: MasterComponent,
                        children: [
                            {
                                path: "",
                                component: InfoComponent
                            },
                            {
                                path: ":id",
                                component: DetailsComponent
                            }
                        ]
                    }
                ]
            }
        ])
    ],
    exports: [
        RouterModule
    ]
})
export class MyRoutingModule { }

So what I would like is to do something like:

this.selectedId = this.route.params.map((params: Params) => params["id"])

Where this.selectedId is an Observable that has the value 1 if the route is /master/1 or the value null if the route is /master.

like image 664
Joel Avatar asked Nov 09 '22 06:11

Joel


1 Answers

Either

this.route.firstChild.params.map(...)

or use a shared service to communicate the params changes from the child to the parent. See https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service for examples.

like image 74
Günter Zöchbauer Avatar answered Nov 15 '22 06:11

Günter Zöchbauer