Mohammad Honari
Mohammad Honari

Reputation: 1

How to define parameter for parent component in Angular 2

I have a class component, that has two subcomponents called students and stats. I have these routes configured for them for now:

const routes: Routes = [
  {
    path: '', component: ClassComponent, children: [
      { path: 'students', component: StudentsComponent },
      { path: 'stats', component: StatsComponent }
    ]
  }
];

And class itself is the child of another component called school.

Now routes are working fine in this level. That is, when browser URL is changed to domain.com/class/students I get students component, and when it's changed to domain.com/class/stats I get stats component.

However, now I need to pass classId as a parameter to the aforementioned routing. I'm stuck at this point, as I have no idea how to include that parameter in routes. Any help is appreciated.

Update: I know that I can have /class/students/1 and /class/stats/1 routes. What I want is to have them like this: /class/1/students and /class/1/stats and also define them only in the class component, not in the children component, and access them both in parent and children components.

Upvotes: 0

Views: 57

Answers (1)

Veselin Davidov
Veselin Davidov

Reputation: 7081

You can do for example:

{ path: "students/:id", component : StudentsComponent }

Then you will have an Id in the url. In the students component (or maybe a different component - for example StudentsDetailsComponent you will need to get that from the ActiveRouter service.

The constructor of the component:

constructor(
  private route: ActivatedRoute

) {}

Then in the code:

  let id = this.route.snapshot.paramMap.get('id');

Check this link https://angular.io/guide/router

Upvotes: 2

Related Questions