0

I have this problem for days and I could not figure this out (also im pretty new in Angular). My goal would be to have an element in a component like this. Lets called this A element:

<button (click)="scroll('anotherComponentsElementId')">Services</button>

the function:

  scroll(id: string) {
    let el = document.getElementById(id);
    console.log(id);
    el!.scrollIntoView();
  }

And then I have an another component, which has the element, where I would like to scroll. Lets call this B element:

<section class="page-section" id='anotherComponentsElementId'>lets gooo</section>

How can I scroll from A element to B element? Currently the code doesnt work, because in the function the id is null. Would you be so kind to help me out?

Balázs Patai
  • 105
  • 1
  • 9
  • Does this answer your question? [Scroll to a specific Element Using html](https://stackoverflow.com/questions/24739126/scroll-to-a-specific-element-using-html) – L777 Mar 04 '22 at 20:09
  • Dear @Le____ ! Thank you for your instantly fast answer. For me for some reason it doesnt work, i have no idea why. Would you be so kind to make a stackblitz if you are confident that it is working? In my case the URL is changing but no "jump to the HTML with or without animation" is shown. – Balázs Patai Mar 04 '22 at 20:18

1 Answers1

1

You can try to add onclick="location.href='#elementid'" in your button.

<input id='top' type="button" onclick="location.href='#A'" value="go to A" />
<input type="button" onclick="location.href='#B'" value="go to B" />
<input type="button" onclick="location.href='#C'" value="go to C" />
<br><br>
<section id='A' style='background:red'>section 1</section>
<p>line</p>
<p>line</p>
<p>line</p>
<p>line</p>
<input type="button" onclick="location.href='#top'" value="back to top" />
<br><br>
<section id='B' style='background:green'>section 2</section>
<p>line</p>
<p>line</p>
<p>line</p>
<p>line</p>
<input type="button" onclick="location.href='#top'" value="back to top" />
<br><br>
<section id='C' style='background:blue'>section 3</section>
<p>line</p>
<p>line</p>
<p>line</p>
<p>line</p>
<input type="button" onclick="location.href='#top'" value="back to top" />
<br><br><br>
L777
  • 7,719
  • 3
  • 38
  • 63
  • I have absolutely no idea why location.href='#elementid'" works but it works. So thank you very much sir! – Balázs Patai Mar 07 '22 at 15:59
  • 1
    Add 'onclick' content in an html tag is the same as add an onlclick eventlistener to the element: the content is read as Javascript. It means `location.href='#top'` is a Javascript line changing the last part of the URL. – L777 Mar 07 '22 at 17:49