0

I have a component that I need to be rendered for numeric routes like /1, /2, /3 etc (where number is :id).

In my component I've declared ngOnInit code

ngOnInit(){
   alert();
}

When first time route changes alert fires, but for other route changes it doesn't. I'm wondering why?

Vnuuk
  • 6,177
  • 12
  • 40
  • 53

2 Answers2

1

If the component is already loaded you should subscribe to changes.

https://stackoverflow.com/a/33548895/2013580

router.events.subscribe((val) => {
        // see also 
        console.log(val instanceof NavigationEnd) 
    });
  }
Community
  • 1
  • 1
zurfyx
  • 31,043
  • 20
  • 111
  • 145
1

You should take the id parameter from the params observable in the ActivatedRoute service.You can do this as follows :

//Component

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

constructor(
  private route: ActivatedRoute      
) {}

ngOnInit(): void {
  this.route.params.subscribe((params: Params) => {
    console.log(params['id']);
    // alert();
  });
}
ranakrunal9
  • 13,320
  • 3
  • 42
  • 43
  • That works great - Thanks! I have one question - if I remove comment from alert in your code and if my route (let's say) is /5 or /10 or whatever. When I refresh page using F5 button it says "ReferenceError: alert is not defined" – Vnuuk Dec 21 '16 at 08:36
  • 1
    `alert` is not part of JavaScript, it's part of the `window` object provided by web browsers so i think it doesn't exist in inside `subscribe` context and because of it its not working – ranakrunal9 Dec 21 '16 at 08:39