Skip to content
Advertisement

How to run Js inside Component

I want to add a parallax effect to a html element in my template html. I have written the code to do this, but not sure about where to implement it to run every time the page scrolls.

let pos = document.body.scrollTop;
document.getElementById('parallex').style.marginTop = '-' + pos + 'px';

I tried Adding this to the ngDoCheck function, but it worked only once. How to do it?

Advertisement

Answer

Angular Provides Host Listeners for this purpose. Best Practice is to use ViewChild to access the html element and renderer2 to update the attributes

HTML

<span #parallex class="parallex">dfd</span>

TS

@ViewChild('parallex')
el: ElementRef;

@HostListener("window:scroll")
onScroll() {
  let pos = window.pageYOffset;
  this.renderer.setStyle(this.el.nativeElement, 'margin-bottom', pos + "px");
  this.renderer.setStyle(this.el.nativeElement, 'margin-left', pos + "px");
}

constructor(
  private renderer: Renderer2
) {}

Checkout this stackblitz for working demo.

Advertisement