2016-07-04 44 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应表示在该函数内部的代码运行时,父宽度不为零。