2

I have a directive which adds the number of pixels corresponding to its parent right css attribute

import { Directive, ElementRef, AfterViewInit } from "angular2/core"

 @Directive({
     selector: "[d]"
 })
 export class PositioningFromParent implements AfterViewInit {
     private el:HTMLElement

    constructor(el: ElementRef) {
        this.el = el.nativeElement
    }

    ngAfterViewInit() {
      let v = this.el.parentNode.getBoundingClientRect().right
      this.el.style[left] = v + "px"
    }
 }

It works just fine. However, if I do resize my window, my parent is changing and its right value as well. My directive doesn't adapt that value at the minute. How could I watch the this.el.parentNode.getBoundingClientRect().right value in Angular2 ?

Thanks

Scipion
  • 11,449
  • 19
  • 74
  • 139

1 Answers1

2

Listen to resize and update when the event is fired:

 @Directive({
     selector: "[d]"
 })
 export class PositioningFromParent implements AfterViewInit {
     private el:HTMLElement

    constructor(el: ElementRef) {
        this.el = el.nativeElement
    }

    ngAfterViewInit() {
      this.updateLeft();
    }

    @HostListener('window:resize') 
    updateLeft() {
      let v = this.el.parentNode.getBoundingClientRect().right
      this.el.style[left] = v + "px"
    }
 }

See also angular2: How to use observables to debounce window:resize to limit the rate the code is executed during resize.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567