George Edwards George Edwards - 1 year ago 104
TypeScript Question

How to trigger an event when component is navigated to?

I have an angular2 application (RC5), where I have a chapter component. This basically has a big template file - chapter.html - which has this:

<div *ngIf="chapter == 1">
<!-- Chapter 1 content -->
<div *ngIf="chapter == 2">
<!-- Chapter 2 content -->
<!-- etc. -->

I then have some arrow buttons for next and for previous chapters. These trigger an event e.g.

if (this.chapter !== '6') {
var next = parseInt(this.chapter) + 1;
let link = ['/tutorial/chapter', next];

So that all works fine, however, the buttons are at the bottom of a chapter, so when they are clicked, the next chapter is displayed, but automatically scrolled down. So on the router click, I would like to trigger an event and scroll to the top of the page, however, as I am navigating to the same component,
isn't triggered.

How can I do this?

Answer Source

If you navigate to the same component, at least a parameter has changed, otherwise the router wouldn't re-navigate.

You can subscribe to parameter changes and invoke scrolling on changes

constructor(private route:ActivatedRoute) {
  this.route.params.forEach(p => this.doScroll());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download