0

I have a angular component with a list of items and want to addEventListner('scroll') to the scrollable parent. Is there a way in pure js to do so?

Let´s say that I want to add a listner on the main content area on https://pr15574-2b2f9e4649baaece71d109477f9b8d8b3b0b428d.ngbuilds.io/tutorial/toh-pt2

Adding the listner to the component works but the actual component is not scrolled, a parent element is, so how do I find the parent that is scrollable? :)

productListComponent.addEventListener('scroll', () => console.log('scroll'));

Mackelito
  • 4,213
  • 5
  • 39
  • 78

1 Answers1

0

Disclaimer: its not recommended for components to attach events outside their own view scope. I will answer your question nonetheless

To get parent element try this answer

Then to attach an event to that parent element, see this answer

I setup an example plunker:

https://plnkr.co/edit/fO3oT74UP1HO8jVrJe5n?p=preview

code:

//our root app component
import {Component, NgModule, VERSION, ElementRef, Renderer} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div style="height:100px; overflow:scroll">
      <h2>Hello {{name}}</h2>
      <child></child>
    </div>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
}

@Component({
  selector: 'child',
  template: `
      <h2>this is child comp</h2>
      <h2>this is child comp</h2>
      <h2>this is child comp</h2>
      <h2>this is child comp</h2>
      <h2>this is child comp</h2>
  `,
})
export class Child{

  constructor(elementRef:ElementRef, renderer: Renderer) {
    var parent = elementRef.nativeElement.parentElement;
    renderer.listen(parent, 'scroll', (event) => {
      console.log(event);
    })
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, Child ],
  bootstrap: [ App ]
})
export class AppModule {}
Community
  • 1
  • 1
Ahmed Musallam
  • 9,523
  • 4
  • 27
  • 47
  • Just to get the parent is no biggie... but how to get the parent that is scrollable? – Mackelito May 18 '17 at 07:08
  • What do you mean "parent that is scrollable"? Are you asking to check if parent is "scrollable" ?? – Ahmed Musallam May 18 '17 at 13:30
  • Nope.. How to find the first parent that is scrollable. I could solve it by iterate all parents until I find the first scrollable. But I´m looking for a more elegant solution :) – Mackelito May 18 '17 at 15:10
  • You'll have to go up the parent tree to find the first scrollable element... if there was an "elegant" solution, it will have to do that anyway.. just abstracted. – Ahmed Musallam May 18 '17 at 16:08
  • Not sure if is a better way but getting the offsetParent worked for me :) – Mackelito May 18 '17 at 18:58