我有一个指令,它增加了与其父right
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
值?
由于
答案 0 :(得分: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以限制调整大小期间执行代码的速率。