Angular 8 scroll to top on route change
Ngày đăng:
10/12/2021
Trả lời:
0
Lượt xem:
121
Angular 2 scroll to top on route change not workingThe router will emit an event when a new component gets loaded in the So in your component with and then in the same component where you placed Wait for the component to initialized component before you start scrolling. So better to put this code under ngAfterViewInit function. ngAfterViewInit() { this.router.events.subscribe((evt) => { if (!(evt instanceof NavigationEnd)) { return; } window.scrollTo(0, 0) }); }This similar issue was faced by me which was due to the style applied to body. i.e. If I removed this style then my layout was badly affected. Instead of removing style I tried below solution and it worked for me... Solution: export class AppComponent implements OnInit { constructor(private router: Router, private changeDetect: ChangeDetectorRef) { } ngOnInit() { this.router.events.subscribe((evt) => { if (!(evt instanceof NavigationEnd)) { return; } // Change height:100% into auto $('body').css('height', 'auto'); // Successfully scroll back to top $('body').scrollTop(0); // Remove javascript added styles $('body').css('height', ''); this.changeDetect.detectChanges(); }); } } |