Angular: how to set component properties using RouterModule class

The Angular Router enables navigation from one view to the next as users perform application tasks.

RouterModule.forRoot creates a module that contains all the directives, the given routes, and the router service itself.

If you want to set a component input field (in this example the property startValue of the CounterComponent component) with the RouterModule.forRoot method, you need to set its value into data property (data is an Observable that contains the data object provided for the route and also contains any resolved values from the resolve guard).

When registered at the root, the module should be set as follows.
app.shared.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './components/app/app.component';
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { CounterComponent } from './components/counter/counter.component';

@NgModule({
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        HomeComponent
    ],
    imports: [
        CommonModule,
        HttpModule,
        FormsModule,
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent,
              data: { startValue: "3" }
            },
            { path: '**', redirectTo: 'home' }
        ])
    ]})

export class AppModuleShared {}

 

Now in your CounterComponent you can read the value using the ActivatedRoute service.

The ActivatedRoute.snapshot contains the data that you set in the ‘data’.
counter.component.ts

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

@Component({
    selector: 'counter',
    templateUrl: './counter.component.html'
})

export class CounterComponent{
    startValue: number
    public currentCount = 0;

    constructor(private route: ActivatedRoute)
    {
        // Read the data property
        this.startValue = route.snapshot.data['startValue'];
        // Set the currentCount with the startValue
        this.currentCount = this.startValue;
    }

    public incrementCounter() {
        this.currentCount++;
    }
}

 

You can also use ActivatedRoute.snapshot to extract the route parameters. For example if you have a parameter called ‘sampleValue’, you can extract it with:

let paramValue = this.route.snapshot.params['sampleValue'];

Leave a comment