1

In my Angular 18 app, I have the following route configuration:

const routes: Routes = [
  ...,
  {
    path: 'test/:year/:month',
    component: ParentComponent,
    children: [
      {
        path: 'child',
        component: ChildComponent
      }
    ]
  },
  ...
]

My RouterModule is also configured to bind the route params to the relevant component inputs:

RouterModule.forRoot(routes, { bindToComponentInputs: true })

I have successfully got this working in my ParentComponent, where I am able to get the two route parameters with the following syntax:

year = input<number>();
month = input<number>();

However, if I try to do the same thing in my ChildComponent (which is rendered within ParentComponent via a router-outlet), I am not able to get values for these two route parameters.

Is there a way to bind these route parameters to the child component's inputs?

2 Answers 2

3

As per the Angular documentation, it is possible to get the parent route info, but do note that it might get confusing if you have complex routes and shared names in the routes.

If you want to use the parent components route info you will need to set the router paramsInheritanceStrategy option: withRouterConfig({paramsInheritanceStrategy: 'always'})

https://angular.dev/guide/routing/common-router-tasks#add-an-input-to-the-component

So, all you would have to do is change the Router config as follows:

RouterModule.forRoot(routes, 
    { 
        bindToComponentInputs: true,
        paramsInheritanceStrategy: 'always' //
    }
)
Sign up to request clarification or add additional context in comments.

Comments

0

RouterModule.forRoot(routes, { bindToComponentInputs: true }) this will bind only local route parameters and not able to access ancestor route parameters.

There might be the several solutions but I recommend to use ActivatedRoute from @angular/router package.

From there, you can access the parent route parameters in the child component by using ActivatedRoute.parent?.snapshot.params.

This will be by design and consistent with Angular's route segment scoping.

I hope this will help you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.