Reputation: 1819
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
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.
constructor()
ngOnChanges()
ngOnInit()
ngDoCheck()
ngAfterContentInit()
ngAfterContentChecked()
ngAfterViewInit()
ngAfterViewChecked()
.ngOnDestroy()
Use the above-highlighted hooks based on your situation.
Please let me know if it does not work.
Upvotes: 2
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