6

Right now I'm making a kind of web shop, and on my home page I've a dropdown of category Let say parent cat A, and sub cats B and C.

Cat A, B and C are all represented by 1 component, CatAComponent. When I go in the first time in one of those cats, my ngoninit gets called and the pages displays what it needs to display.

When I want to click on another sub cat, I'm still on the same component, but only a param of the route changes ( e.g. I was on localhost:123/CatA/CatB, now I'm on localhost:123/CatA/CatC, only a parameter changed so the ngOnInit does not get called and my update method does not get called neither).

Any way to go around this? I can't put a (click) method in my view file to reference the method, the menu for categories is in another viewcomponent.

Can I call an NgOnInit when only a parameter has changed?

TanguyB
  • 1,954
  • 3
  • 21
  • 40

1 Answers1

18

You have to subscribe to ActivatedRoute service as follows :

//Component

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

export class YourComponent {
  constructor(
    private route: ActivatedRoute      
  ) {}

  ngOnInit(): void {
    this.route.params.subscribe((params: Params) => {
      console.log(params); 
      // this will be called every time route changes
      // so you can perform your functionality here

    });
  }
}
ranakrunal9
  • 13,320
  • 3
  • 42
  • 43
  • I'm silly. I had subscribed to the params, put put my update method outside of it instead of in it. Thanks worked perfectly – TanguyB Dec 23 '16 at 11:46
  • 2
    This answer deals with params, not entire route. For routes, go here https://stackoverflow.com/questions/42453375/how-to-call-a-function-on-every-rotute-change-in-angular2 – dasfdsa Aug 18 '17 at 11:14
  • You should also save the subscription in an instance variable and unsubscribe in an ngOnDestroy method. – AlanObject Aug 22 '18 at 17:09