Is there a way to easily monitor the scroll position of the browser and inform multiple components about it?
For example, I would like to dynamically change the classes of different elements on the page as the user scrolls. In the past, with older versions of Angular and jQuery, this was achievable with the help of plugins. While it is possible to implement this functionality using vanilla JavaScript and emitting events on application start, it can be messy and inefficient.
What are some alternative solutions to tackle this problem?
UPDATE (following suggestions):
Here is my attempt at solving this:
I created a new component:
import {Component} from "angular2/core";
@Component({
selector: '[track-scroll]',
host: {'(window:scroll)': 'track($event)'},
template: ''
})
export class TrackScrollComponent {
track($event) {
console.debug("Scroll Event", $event);
}
}
Then I added an attribute to the main directive of my application:
<priz-app track-scroll>
Furthermore, I included the component as one of the providers in the top component:
import {TrackScrollComponent} from "../../shared/components/track-scroll.component";
@Component({
selector: 'priz-app',
moduleId: module.id,
templateUrl: './app.component.html',
directives: [ROUTER_DIRECTIVES, SecureRouterOutlet, AppHeader, TrackScrollComponent],
providers: [AuthenticationService]
})
Unfortunately, it did not yield the expected results...
ANOTHER UPDATE:
I moved the track-scroll
attribute to one of the div elements within the main template:
<div class="container-fluid" track-scroll>
<div class="row">
<div class="col-md-12">
<app-header></app-header>
<secure-outlet signin="Login" unauthorized="AccessDenied"></secure-outlet>
</div>
</div>
</div>
As a result, the application loads with a blank screen. Exciting times...
FINAL SOLUTION (that worked for me).
- Create a directive:
import {Directive} from "angular2/core";
@Directive({
selector: '[track-scroll]',
host: {'(window:scroll)': 'track($event)'}
})
export class TrackScrollDirective {
track($event: Event) {
console.debug("Scroll Event", $event);
}
}
- Include the directive in all components that require it:
directives: [TrackScrollDirective]
- Assign the attribute to each element that needs to track the event:
<div class="col-md-12" track-scroll>