Note that there are differences between Query parameter and Route parameter. Query parameters are optional. The missing parameter does not stop angular from navigating to the route
Passing Query Parameters
<a [routerLink]="['product-list']" [queryParams]="{ page: 99 }">Go to Page 99</a>
this.router.navigate(['/product-list'], { queryParams: { page: pageNum } });
servers.component.html
<div class="row"> <div class="col-xs-12 col-sm-4"> <div class="list-group"> <a [routerLink]="['/servers',5,'edit']" [fragment]="'loading'" href="#" class="list-group-item" *ngFor="let server of servers"> {{ server.name }} </a> </div> </div> <div class="col-xs-12 col-sm-4"> <button class="btn btn-primary" (click)="onReload()">Reload Page</button> <app-edit-server></app-edit-server> <hr> <app-server></app-server> </div> </div>
output
http://localhost:4200/servers/5/edit#loading
Do all the above Programmatically :
home.component.ts
import {Component, OnInit} from '@angular/core'; import {Router} from '@angular/router'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { constructor(private router: Router) { } ngOnInit() { } onLoadServer(id: number) { this.router.navigate(['/servers', id, 'edit'], {queryParams: {allowEdit: '1'}, fragment: 'loading'}); } }
output
http://localhost:4200/servers/1/edit?allowEdit=1#loading
Retrieve Params
edit-server.component.ts
import {Component, OnInit} from '@angular/core'; import {ServersService} from '../servers.service'; import {ActivatedRoute, Params} from '@angular/router'; @Component({ selector: 'app-edit-server', templateUrl: './edit-server.component.html', styleUrls: ['./edit-server.component.css'] }) export class EditServerComponent implements OnInit { server: { id: number, name: string, status: string }; serverName = ''; serverStatus = ''; constructor(private serversService: ServersService, private route: ActivatedRoute) { } ngOnInit() { // retrieve params on initializing console.log(this.route.snapshot.queryParams); console.log(this.route.snapshot.fragment); // retrieve params on changes this.route.queryParams.subscribe((value: Params) => { console.log(value); }); this.route.fragment.subscribe((value: string) => { console.log(value); }); this.server = this.serversService.getServer(1); this.serverName = this.server.name; this.serverStatus = this.server.status; } onUpdateServer() { this.serversService.updateServer(this.server.id, {name: this.serverName, status: this.serverStatus}); } }
References
https://angular.io/guide/router#query-parameters-and-fragments
https://www.tektutorialshub.com/angular/angular-passing-optional-query-parameters-to-route/
https://angular-2-training-book.rangle.io/routing/query_params