2016-07-04 49 views
1

我想根據它的父親而不是瀏覽器通過postioned來擁有一個固定元素。因此,我已經設計了一個(快速和骯髒的)angular2指令:Angular2:有一個固定元素根據它的父親定位

我的模板

<div class="main" style="position: relative"> 
     <div style="position: absolute" positioningFromParent="left" [additionalPixels]=20> 
      ... 
     </div> 
</div> 

我Angular2指令

import { Directive, ElementRef, Input, OnInit } from "angular2/core" 

@Directive({ 
    selector: "[positioningFromParent]" 
}) 
export class PositioningFromParent implements OnInit { 
    private el:HTMLElement 
    @Input() positioningFromParent: string = "" 
    @Input() additionalPixels: number = 0 

    constructor(el: ElementRef) { 
     this.el = el.nativeElement 
    } 
    ngOnInit() { 
    let v = this.el.parentNode.getBoundingClientRect()[this.positioningFromParent] 
    this.el.style[this.positioningFromParent] = (v + this.additionalPixels).toString() + "px" 
    } 
} 

但是,它並沒有爲我的主要元素的寬度工作動態設置(我無法指定它)。當ngOnInit運行時,它會給我一個寬度爲0的寬度,因爲它的寬度只會在後面出現。我怎麼能在angular2中「觀察」父母的寬度?

感謝

回答

1

的看法是不ngOnInit()使用ngAfterViewInit(),而不是準備好了。

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

@Directive({ 
    selector: "[positioningFromParent]" 
}) 
export class PositioningFromParent implements AfterViewInit { 
    private el:HTMLElement 
    @Input() positioningFromParent: string = "" 
    @Input() additionalPixels: number = 0 

    constructor(el: ElementRef) { 
     this.el = el.nativeElement 
    } 
    ngAfterViewInit() { 
    let v = this.el.parentNode.getBoundingClientRect()[this.positioningFromParent] 
    this.el.style[this.positioningFromParent] = (v + this.additionalPixels).toString() + "px" 
    } 
} 
1

您應該使用ngAfterViewInit生命週期掛鉤,而不是ngOnInit,因爲這將實際的DOM元素已經被創建之後被調用(ngOnInit時才調用組件的輸入已經解決)。使用ngAfterViewInit應表示在該函數內部的代碼運行時,父寬度不爲零。