Article
home/blog/Loading

Calculate the remaining scroll distance in Angular

To Calculate the remaining scrollbar distance in Angular you need to perform some simple calculations on various window and document variables.

1. Inject window and document

 constructor(
        @Inject('Window') window: Window,
        @Inject('Document') document: Document
    ) {

2. Listen to the scroll event

window.addEventListener('scroll', () => {
            const scrollRemainder = (document.documentElement.scrollHeight - (window.pageYOffset + window.innerHeight));
            console.log('remaining scroll px: ', scrollRemainder)
        });

Worth noting

If Angular complains that there is no provider for Window and/or Document then you need to add the provider to the @NgModule.

For Example

@NgModule({
    declarations: [
        //snip
    ],
    imports: [
        //snip
    ],
    providers: [
        { provide: 'Window', useValue: window }, // add the provider
        { provide: 'Document', useValue: document } // add the provider
    ],
    bootstrap: [
        // snip
    ]
})