I've seen some implement a component, which you can can do but this expects (to my knowledge) an html template. I've used instead directive (which a component is but without the requirement of having an associated html template).
Here is my directive:
import { HostListener, Component, OnChanges, Directive, Input, Output, EventEmitter, SimpleChange, ElementRef} from '@angular/core';
@Directive({
selector: '[track-scroll]',
//host: {'(window:scroll)': 'track($event)'},
})
export class TrackScrollComponent {
@HostListener('scroll', [''])
track() {
console.debug("Scroll Event");
console.debug(this._elementRef.nativeElement.scrollTop);
}
constructor(private _elementRef: ElementRef) {}
}
I did use injection of the Element Ref, or as it is instanced from the 'div' tag the div ElementRef.
All directives in RC 6.0 (?) + go to the ngModule, or otherwise assigned in parent component.
Thus in my app.module.ts
@NgModule({
imports: [ BrowserModule, AppRouting ],
declarations: [TrackScrollComponent],
bootstrap: [ App ]
})
Implementing in your component then goes to yourcomponent.html or template as follows:
<div track-scroll> </div>
Here is my directive:
import { HostListener, Component, OnChanges, Directive, Input, Output, EventEmitter, SimpleChange, ElementRef} from '@angular/core';
@Directive({
selector: '[track-scroll]',
//host: {'(window:scroll)': 'track($event)'},
})
export class TrackScrollComponent {
@HostListener('scroll', [''])
track() {
console.debug("Scroll Event");
console.debug(this._elementRef.nativeElement.scrollTop);
}
constructor(private _elementRef: ElementRef) {}
}
I did use injection of the Element Ref, or as it is instanced from the 'div' tag the div ElementRef.
All directives in RC 6.0 (?) + go to the ngModule, or otherwise assigned in parent component.
Thus in my app.module.ts
@NgModule({
imports: [ BrowserModule, AppRouting ],
declarations: [TrackScrollComponent],
bootstrap: [ App ]
})
Implementing in your component then goes to yourcomponent.html or template as follows:
<div track-scroll> </div>
Sorry for some of the imports I hadn't tested which one were exclusively needed for this howTo.
There is mentions about not working directly with ElementRef, but at the moment I wanted to provide clarity for solution as opposed to creating added confusion for something that really should be simple.
No comments:
Post a Comment