The Angular Router enables navigation from one view to the next as users perform application tasks. If we need to pass one or more query string parameters to our next view component, we need to divide our parameters into the routing path with ‘/:’

For example, our app.routing.ts should contains:

RouterModule.forRoot([ 
{ path: 'homewithparames/:id/:name', component: HomeComponent }, 
{ path: "servicedenied", component: AccessDeniedComponent }, 
{ path: "accessodenied", component: AccessDeniedComponent },
])

And into the ngOnInit() method of the HomeComponent.ts we can read query parameters with the ActivatedRoute paramMap subscription:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute} from '@angular/router'; 

@Component({ 
selector: 'app-home', 
templateUrl: './home.component.html',
})

export class HomeComponent implements OnInit
{ 
constructor(private route: ActivatedRoute ) {
 } 

ngOnInit() { 
this.route.paramMap.subscribe(result =>
 {
 console.log(`id: ${result.get('id')}`); 
 console.log(`name: ${result.get('name')}`); 
 });  }
}

So, if we call ‘http://localhost:4200/homewithparames/123/Marco‘, the console output will be :

id: 123
name: Marco

Read also : How to get the current year using typescript in angular 6

Tagged:

Laisser un commentaire