2016-07-05 4 views
2

私はその親right CSS属性Angular2見て、親のCSS属性

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

それだけで正常に動作に対応する画素の数を追加するディレクティブを持っています。しかし、私は私のウィンドウのサイズを変更する場合、私の親は変化しており、そのright値も同様です。私のディレクティブはその分の値を分単位で適応させません。 Angular2でthis.el.parentNode.getBoundingClientRect().rightの値を見るにはどうすればよいですか?

おかげ

答えて

2

は、イベントが発生したときにサイズを変更し、更新するために聞く:

@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" 
    } 
} 

コードがサイズ変更中に実行される速度を制限することもangular2: How to use observables to debounce window:resizeを参照してください。