html - Angular2: Có một phần tử cố định được định vị liên quan đến phần tử cha của nó
Tôi muốn có một phần tử cố định được định vị theo phần tử cha của nó chứ không phải theo trình duyệt. Do đó, tôi đã thiết kế một directive angular2 (nhanh và thô sơ):
Mẫu của tôi
<div class="main" style="position: relative">
<div style="position: absolute" positioningFromParent="left" [additionalPixels]=20>
...
</div>
</div>
Chỉ thị Angular2 của tôi
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"
}
}
Tuy nhiên, nó không hoạt động vì chiều rộng của phần tử chính của tôi được đặt một cách động (tôi không thể chỉ định nó). Khi ngOnInit chạy, nó trả về chiều rộng là 0 vì chiều rộng chỉ xuất hiện sau đó. Làm thế nào tôi có thể "theo dõi" chiều rộng của phần tử cha trong angular2?
Cảm ơn
Câu trả lời #1
Giao diện chưa sẵn sàng trong ngOnInit(), hãy sử dụng ngAfterViewInit() thay vào đó.
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"
}
}
Câu trả lời #2
Bạn nên sử dụng hook vòng đời ngAfterViewInit thay vì ngOnInit, vì hook này sẽ được gọi sau khi các phần tử DOM thực sự đã được tạo (ngOnInit chỉ được gọi khi các input của component đã được giải quyết). Sử dụng ngAfterViewInit nghĩa là chiều rộng của phần tử cha sẽ khác 0 vào thời điểm mã bên trong hàm đó chạy.
