I'm trying to create a directive that will fadeIn a photo slowly when an element is made visible. To do so, my first idea is comparing the position of an item regarding to the top (also checking the height of the window). But I can find how to do that with Angular2.
This is my code so far:
import {Directive, ElementRef, Renderer} from 'angular2/core';
@Directive({
selector: '[fadeInPhoto]',
host: {
'(window:scroll)': 'onScroll()'
}
})
export class FadeInPhotoDirective{
private scrollTop: number;
private initialClass: string;
constructor(private _el: ElementRef, private _renderer: Renderer){
this.initialClass = 'thumbnail';
}
onScroll(){
console.log('Photo top:', this._el);
}
}
But this._el doesn't seem to have any method or property that contains that information.
"offsetTop is relative to it's place in the document, not relative to the view port." -See link below
I was able to get the ACTUAL offsetTop from the top of the document using:
this.element.nativeElement.getBoundingClientRect().top
See: https://stackoverflow.com/a/40877754/1742393
The Renderer
provides a selection of methods but AFAIK offsetTop
is not one of them (they are all just to set values, not to get ones).
You can use instead:
this._el.nativeElement.offsetTop
Try to do it like this:
make sure to declare the element into the constructor, as "private":
constructor(private el: ElementRef) { ...}
make sure you get the offsetTop after the element(s) already exist on the page:
ngAfterViewInit() { console.log('el.nativeElement: ', this.el.nativeElement.offsetTop); }
Try using a refrence in your template instead:
<div id='gallery-container' #galleryContainer class='gallery-image-container'>
<div> <img src="../pic1"></div>
<div> <img src="../pic2"></div>
<div> <img src="../pic3"></div>
</div>
And use the ref name as the argument:
@ViewChild('galleryContainer') galleryContainer: ElementRef;
don't Forgot to mention that any view child thus declared is only available after the view is initialized. The first time this happens is in ngAfterViewInit (import and implement the AfterViewInit interface).
then in your template just call the method like this:
<div class="arrow " (click)="topArrowEffect()" ></div>
and in your controller your method should be like this:
topArrowEffect(){
this.galleryContainer.nativeElement.scrollTop =10;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With