1

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>
<div *ngIf="chapter == 2">
<!-- Chapter 2 content -->
</div>
<!-- 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;
  console.log(next);
  let link = ['/tutorial/chapter', next];
  this.router.navigate(link);
}

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, ngOnInit() isn't triggered.

How can I do this?

George Edwards
  • 8,979
  • 20
  • 78
  • 161

2 Answers2

2

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());
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
2
constructor(private route:ActivatedRoute) {
  this.route.params.subscribe(params => {
        //do your stuffs...
  });
}    
micronyks
  • 54,797
  • 15
  • 112
  • 146