How to do it...

To add a child route to our router module, we will need to update its route configuration:

  1. First, we must define children routes using the children property in the route configuration:
RouterModule.forRoot([
...
{
path: "posts",
component: PostsComponent,
children: [{
path: ":id",
component: PostComponent
}]
}
...
])
  1. Once we have set up our child route, we can retrieve our ID parameter in our new PostComponent.ts using the ActivatedRoute class from the Angular router:
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from "@angular/router";

@Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit {
postId = null;
constructor(private route:ActivatedRoute) {
route.params.subscribe(
params =>{
this.postId = parseInt(params['id']);
}

);
}
}
  1. Now that we have the ID parameter, we can use it in our template:
<p>
post works! - {{postId}}
</p>
  1. Finally, we will also need to provide another outlet within the template of PostsComponent to surface our specific post template:
<p>
posts works!
</p>

<router-outlet></router-outlet>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.111.233