Skip to content

Commit d63a8d2

Browse files
committed
feat: IntersectionService
1 parent affd956 commit d63a8d2

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { TestBed } from '@angular/core/testing';
2+
3+
import { IntersectionService } from './intersection.service';
4+
5+
describe('IntersectionService', () => {
6+
let service: IntersectionService;
7+
8+
beforeEach(() => {
9+
TestBed.configureTestingModule({
10+
imports: [IntersectionService]
11+
});
12+
service = new IntersectionService();
13+
// service = TestBed.inject(IntersectionService);
14+
});
15+
16+
it('should be created', () => {
17+
expect(service).toBeTruthy();
18+
});
19+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { Injectable, OnDestroy } from '@angular/core';
2+
import { BehaviorSubject } from 'rxjs';
3+
4+
@Injectable()
5+
export class IntersectionService implements OnDestroy {
6+
7+
constructor() { }
8+
9+
private intersecting = new BehaviorSubject<boolean>(false);
10+
intersecting$ = this.intersecting.asObservable();
11+
12+
private intersectionObserver!: IntersectionObserver;
13+
private hostElement!: { nativeElement: Element; };
14+
15+
createIntersectionObserver(hostElement: { nativeElement: Element; }) {
16+
17+
this.hostElement = hostElement;
18+
19+
const options = {
20+
root: null,
21+
rootMargin: '0px',
22+
threshold: 0.2
23+
};
24+
25+
const handleIntersect = (entries: any[], observer: any) => {
26+
entries.forEach((entry: any) => {
27+
this.intersecting.next(entry.isIntersecting);
28+
});
29+
};
30+
31+
this.intersectionObserver = new IntersectionObserver(handleIntersect, options);
32+
this.intersectionObserver.observe(hostElement.nativeElement);
33+
}
34+
35+
ngOnDestroy(): void {
36+
this.intersectionObserver?.unobserve(this.hostElement?.nativeElement);
37+
}
38+
}

0 commit comments

Comments
 (0)