As I would like to use the fade-in on scroll feature you can see on many websites, I would like to know how to implement such functionality in my application the "angular way". I already have a component implementation that works and maybe this helps anyone who has the same need of using this fade-in on scroll behavior.
My problem with the (shortened) code below is that it does not support Dependency Injection as it always creates a new Instance of the IntersectionObserver.
import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
@Constructor({
selector: 'app-cv',
template: `<div class="entry-content"></div>`
})
export class CurriculumVitaeComponent implements OnInit, AfterViewInit, OnDestroy {
public iIntersectionObserver :IntersectionObserver;
constructor() {}
ngOnInit() :void {
this.iIntersectionObserver = new IntersectionObserver(entries => {
console.log(entries); // your code here e.g. toggling classes with Renderer2
}, { root: null, rootMargin: '0px', threshold: [0, .25, .5, .75, 1]});
}
ngAfterViewInit() :void {
const tEntry :Element = document.querySelector('.entry-content');
this.iIntersectionObserver.observe(tEntry);
}
ngOnDestroy() :void {
this.iIntersectionObserver.disconnect(); // I'm lazy you could also save the ref and unobserve the Element
}
}
As you can see this perfectly works, but it is too much setup for multiple components and it does not use dependency injection at all. Is there a way to configure this, maybe with a Service or a Factory Provider?
These are some links I stumbled upon my research, but I did not know how to implement such a specific case:
Provide new instances of model class for dependency injection in Angular 2
Create new instance of class that has dependencies, not understanding factory provider