Reloading components when route parameters change in Angular

A simple way to reload component data when route params change in Angular

Posted on April 29, 2020

Tags:

Angular

Angular does not reload components by default when route parameters change if the route itself stays the same.

This is particular problem when, say for example, you have a list of products on a page e.g. /product/:id.
Switching between products will keep the route, /product/, the same but just update the id. In this scenario the URL will be updated but Angular won’t refresh the component or data.

The simplest way to refresh the component data is to subscribe to the snapshot of the active route and call your init method when parameters change, as shown below.

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

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

    constructor(
        private _activatedRoute: ActivatedRoute
    ) {
        this._activatedRoute.paramMap.subscribe(params => {
            this.ngOnInit();
        });
    }

    ngOnInit() {
        this.getData();
        // Do something else
    }

    getData() {
        // Get some data
    }

}