Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
180
rated 0 times [  184] [ 4]  / answers: 1 / hits: 46714  / 7 Years ago, thu, august 17, 2017, 12:00:00

Upon clicking a button (which is bottom of the page), I want to go to a certain element (in my case, #navbar) which is in the top of the current page, but I don't know how to do it. I've tried the following code with no avail.



<nav class=navbar navbar-light bg-faded id=navbar>
<a class=navbar-brand href=#>
{{appTitle}}
</a>
<!-- rest of the nav link -->
</nav>
<!-- rest of the page content -->

<!-- bottom of the page -->
<button class=btn btn-outline-secondary (click)=gotoTop()>Top</button>


In angular component:



import { Router } from '@angular/router';
/* rest of the import statements */
export class MyComponent {
/* rest of the component code */
gotoTop(){
this.router.navigate([], { fragment: 'navbar' });
}
}


I would really appreciate if someone helped me out with a solution and explained why my code hadn't worked.



Please note that element (navbar) is in other component.


More From » angular

 Answers
5

You can do this with javascript:



gotoTop() {
let el = document.getElementById('navbar');
el.scrollTop = el.scrollHeight;
}


This will bring the DOM element with id=navbar into view when the method is called. There's also the option of using Element.scrollIntoView. This can provide a smooth animation and looks nice, but isn't supported on older browsers.



If the element is in a different component you can reference it several different ways as seen in this question.



The easiest method for your case would likely be:



import { ElementRef } from '@angular/core'; // at the top of component.ts

constructor(myElement: ElementRef) { ... } // in your export class MyComponent block


and finally



gotoTop() {
let el = this.myElement.nativeElement.querySelector('nav');
el.scrollIntoView();
}


Working plunker.


[#56727] Tuesday, August 15, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
bradleymoisesy

Total Points: 121
Total Questions: 105
Total Answers: 95

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
bradleymoisesy questions
Wed, Dec 22, 21, 00:00, 2 Years ago
Tue, Jun 1, 21, 00:00, 3 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
Thu, Jan 16, 20, 00:00, 4 Years ago
;