Angular Route Query parameters and Fragment
How to handle Query parameter and fragment
Query parameter http://localhost:4200/param?key=value#stg
key=value is a query parameter.
#stg is fragment.
About Angular routing, please read Angular Route
Routing file
This is same as last entry
import { ModuleWithProviders } from '@angular/core'; import { RouterModule } from '@angular/router'; import { MainComponent } from './main.component'; import { ParamComponent } from './param.component'; import { ContentComponent } from './content.component'; import { NotfoundComponent } from './notfound.component'; import { ChildpageComponent } from './childpage.component'; import { DataComponent } from './data.component'; const Routes = [ { path: '', component: MainComponent }, { path: 'main', component: MainComponent }, { path: 'param', component: ParamComponent }, { path: 'data', component: DataComponent, data: { category: 'Angular'} }, { path: 'contents/:id', component: ContentComponent, children: [ { path: 'pages/:page', component: ChildpageComponent } ]}, { path: 'top', redirectTo: 'main', pathMatch: 'full' }, { path: '**', component: NotfoundComponent } ]; export const APP_ROUTES: ModuleWithProviders = RouterModule.forRoot(Routes);
In this time, we focus on
{ path: 'param', component: ParamComponent }
Catch in component
param.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ template: ` <h2>Parameter</h2> <ul> <li>Query : {{query}}</li> <li>Fragment : {{fragment}}</li> </ul> ` }) export class ParamComponent implements OnInit { query = ''; fragment = ''; constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.queryParams.subscribe( params => this.query = params['key'] ); this.route.fragment.subscribe( frag => this.fragment = frag ); } }
We can get query parameters and fragment from ActivatedRoute.