Angular 2: getting RouteParams from parent component

前端 未结 13 965
暖寄归人
暖寄归人 2020-11-28 04:47

How do I get the RouteParams from a parent component?

App.ts:

@Component({
  ...
})

@RouteConfig([
  {path: \'/\', component: HomeCompo         


        
13条回答
  •  悲&欢浪女
    2020-11-28 05:01

    UPDATE:

    Now that Angular2 final was officially released, the correct way to do this is the following:

    export class ChildComponent {
    
        private sub: any;
    
        private parentRouteId: number;
    
        constructor(private route: ActivatedRoute) { }
    
        ngOnInit() {
            this.sub = this.route.parent.params.subscribe(params => {
                this.parentRouteId = +params["id"];
            });
        }
    
        ngOnDestroy() {
            this.sub.unsubscribe();
        }
    }
    

    ORIGINAL:

    Here is how i did it using the "@angular/router": "3.0.0-alpha.6" package:

    export class ChildComponent {
    
        private sub: any;
    
        private parentRouteId: number;
    
        constructor(
            private router: Router,
            private route: ActivatedRoute) {
        }
    
        ngOnInit() {
            this.sub = this.router.routerState.parent(this.route).params.subscribe(params => {
                this.parentRouteId = +params["id"];
            });
        }
    
        ngOnDestroy() {
            this.sub.unsubscribe();
        }
    }
    

    In this example the route has the following format: /parent/:id/child/:childid

    export const routes: RouterConfig = [
        {
            path: '/parent/:id',
            component: ParentComponent,
            children: [
                { path: '/child/:childid', component: ChildComponent }]
        }
    ];
    

提交回复
热议问题