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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.