2016-07-05 70 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限制大小調整過程中執行的代碼的速度。