Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get in Angular2 the offSetTop of an element without using jQuery

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.

like image 567
Fabiot Avatar asked Mar 09 '16 18:03

Fabiot


4 Answers

"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

like image 144
rbj325 Avatar answered Nov 13 '22 17:11

rbj325


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
like image 45
Günter Zöchbauer Avatar answered Nov 13 '22 15:11

Günter Zöchbauer


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); }

like image 1
decebal Avatar answered Nov 13 '22 15:11

decebal


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;
}
like image 1
Zahra Shokrian Avatar answered Nov 13 '22 15:11

Zahra Shokrian