Angular 11 ActivatedRoute params – Get full params list

Just updated ng-router-state-params to Angular 11.

Error

I want the full route parameters inside my component.

The Fix

Install ng-router-state-params as a service provider. The default Router and RouterModule does not provide any access to the active state or state params to all components, only the target component. This service will watch the events of the RouterModule, parse them, and provide them as a value or an observable to any component that needs it.

Example

Install using npm:

npm install ng-router-state-params
 // app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { Router } from '@angular/router';

import { AppComponent } from './app.component';

import { AppRoutingModule } from './app-routing.module';

import { RouterStateParamsService } from 'ng-router-state-params';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    AppRoutingModule,
    BrowserModule,
    HttpModule
  ],
  providers: [
    RouterStateParamsService
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}
 // top-nav/top-nav.component.ts
import { Component, OnInit } from '@angular/core';

import { RouterStateParamsService }  from 'ng-router-state-params';

@Component({
  selector: 'top-nav',
  templateUrl: './top-nav.component.html',
  styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {

  constructor(public routerStateParamsService: RouterStateParamsService) { }

  ngOnInit() {
    this.routerStateParamsService.getParams().subscribe( val => {
      console.log("top nav params", val);
    });

    this.routerStateParamsService.getUrl().subscribe( val => {
      console.log("top nav url", val);
    });

    this.routerStateParamsService.getConfig().subscribe( val => {
      console.log("top nav config", val);
    });

    this.routerStateParamsService.getRoute().subscribe( val => {
      console.log("top nav route", val);
    });
  }

}

Now we have access and can subscribe to route changes in our top-nav component. This is useful for setting the page title, showing breadcrumbs, modifying the menu based on what’s visible below.

ng-router-state-params

github: https://github.com/stomo21/ng-router-state-params

npm: https://www.npmjs.com/package/ng-router-state-params

Share this:

Leave a comment

18 + 17 =