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

Viewed 39900

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.

7 Answers

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

in html:

<div (click)="getPosition($event)">xxx</div>

in typescript:

getPosition(event){
    let offsetLeft = 0;
    let offsetTop = 0;

    let el = event.srcElement;

    while(el){
        offsetLeft += el.offsetLeft;
        offsetTop += el.offsetTop;
        el = el.parentElement;
    }
    return { offsetTop:offsetTop , offsetLeft:offsetLeft }
}

Try to do it like this:

import { Component, OnInit, HostListener, ViewChild } from '@angular/core';


    @ViewChild("pageMenu")
      menuStickyElement;

     @HostListener("window:scroll", [])
      sticklyMenu() {
        // Get top height 
        this. offsetTop = document.documentElement.scrollTop
        if (document.documentElement.scrollTop >= this.menuStickyElement.nativeElement.offsetTop) {
          this.stickyNavMenu = true;
        } else {
          this.stickyNavMenu = false;
        }
      }
Related