0

I have the following:

main.module.ts

//Importing "my_section"
...
import { my_section } from './my_section';

@NgModule({
   declarations: [...],
   imports: [..., my_section],
   exports: [...]
})
export class main_pageModule {}

main.html

 //As an example, let say I have three "my_section"
<div class="top">
    <my_section></my_section>
    <my_section></my_section>
    <my_section></my_section>
</div>

Then,

my_section.ts

...
@Component({
  selector: 'my_section',
  templateUrl: 'my_section.html'
})

export class my_section{
 ...
}

This is a simplified version of it: As you can see, <my_section></my_section> is imported from my_section.ts into main.module.ts.

I am trying to trigger a function when each <my_section></my_section> is in view.

I tried to use ViewChild, but no luck.

Any idea how I can detect when a custom element is in view?

Thanks!

Steve Kim
  • 5,293
  • 16
  • 54
  • 99
  • Possible duplicate of [Angular check when an element is in view](https://stackoverflow.com/questions/49215634/angular-check-when-an-element-is-in-view) – David Mar 11 '18 at 07:05
  • DId you try using `getBoundingClientRect` ? Or IntersectionObserver API? https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API – David Mar 11 '18 at 07:08

1 Answers1

1

Try to use ViewChildren decorator in your component (not in module as in your example):

import { AfterViewInit, Component, QueryList, ViewChildren } from '@angular/core';
import { my_section } from './my_section';

...

class <YOUR_COMPONENT_NAME> implements AfterViewInit {
  @ViewChildren(my_section) mySections: QueryList<my_section>;

  ngAfterViewInit() {
    // mySections are set at this stage

    // you may listen to mySections change
    this.mySections.changes.subscribe(section => {    
      // section is available
    });

    // or just iterate over available sections
    this.mySections.forEach(section => {    
      // section is available
    });
  }
}
Andriy
  • 14,781
  • 4
  • 46
  • 50