Skip to content
Advertisement

How to pass id parameter to child route?

I have the following route config and in this example, I can get the id parameter in the StudentComponent by using the route functions.

However, I need to pass this id parameter to the child route of this component, but I am not sure if I have to update the following config to pass this id parameter to the EducationComponent.

Should I use the same approach in StudentComponent also in the EducationComponent as well?

{
  path: 'student/:id',
  component: StudentComponent,
  children: [
    {
      path: '',
      redirectTo: 'education',
    },
    {
      path: 'education',
      component: EducationComponent      
    }
  ]
}

Advertisement

Answer

You have several options and the best choice depends on your application architecture.

From the way your app-routing.module.ts file is configured, the route that exposes the id parameter variable is a parent route of the two children you’ve shown. So you have a parent-to-child relationship of some sort. You can also look at this as a component-to-component relationship (or a one-to-many relationship), even though your routing strategy suggests that you may not want to do that.

As in other parent-to-child component relationships, you’re able to use the @Input decorator and an input value to do something like the following to pass a value maintained or known to the ParentComponent to the ChildComponent. The ParentComponent would access this parameter from a Router Snapshot or utilizing another strategy like the ActivatedRoute params.

<app-parent-component>
  <app-child-component [id]="variableNameInChildComponent"></app-child-component>
</app-parent-component>

(See https://angular.io/guide/component-interaction)

Alternatively, you could create a data store for the id value for when it’s retrieved, updated, etc.

Storing data in a way that other components might access is probably more appropriate when components have a one-to-many relationship of some sort. For id, it would mean that other components outside of the StudentComponent tree leverage that value as well. In that way, you can inject code of a service into many components and utilize those values throughout the application, depending on the module pattern, which isn’t clear from this routing strategy snippet.

The location of this data store for your id, or whatever you’re storing, depends on how ubiquitous the value is within your application. If the student’s id is used throughout the application, then a Service file with a (Behavior)Subject sounds great. If the student id is used for the child component, you could handle the value state in a more constricted way with a get request from your app-parent-component from within a Service.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement