L. Heider
L. Heider

Reputation: 1819

Is there a way to detect if a component is viewed by the user?

In my chat application I want to mark the messages with a "is read" flag. But only if the component is alive (means between init and destroy) doesn't really mean that the user has seen it. Since he could be browsing in another tab or minimized the window etc.

So is there any common way to detect if a specific component in angular is displayed on the screen and focused?

Upvotes: 0

Views: 3224

Answers (2)

Tilak Dewangan
Tilak Dewangan

Reputation: 361

If you want to check, whether or not your child component is checked/viewed, then please use Angular Life Cycle Hooks in child component.

  1. constructor()
  2. ngOnChanges()
  3. ngOnInit()
  4. ngDoCheck()
  5. ngAfterContentInit()
  6. ngAfterContentChecked()
  7. ngAfterViewInit()
  8. ngAfterViewChecked().
  9. ngOnDestroy()

Use the above-highlighted hooks based on your situation.

Please let me know if it does not work.

Upvotes: 2

L. Heider
L. Heider

Reputation: 1819

I finally found a library which solves this problem: ngx-page-visibility

(supports Angular >= 6.x and rxjs >= 6.x)

Here a short demonstration:

 @OnPageVisible()
 logWhenPageVisible(): void {
    console.log( 'OnPageVisible' );
    console.log( 'visible' );
 }

Or simply do:

    document.addEventListener('visibilitychange', () => {
      if (document.hidden) {
        console.log('document is hidden');
      } else {
        console.log('document is showing');
      }
    });

Upvotes: 1

Related Questions