2017-04-26 45 views
0

我有一個「彈出」顯示從mousemove上的數據庫檢索到的數據,並出現在鼠標位置。它看起來像這樣:角度2:從DOM獲取彈出高度

<div (mousemove)="onMouseMove($event)></div> 

onMouseMove(event: MouseEvent) { 
    this.xCoord = event.x 
    this.yCoord = event.y 
} 

<div [style.left.px]="xCoord" [style.top.px]="yCoord" class="popup"> 
    ... 
</div> 

由於彈出窗口的尺寸是動態的,根據它的內容,我需要檢索的尺寸,以便在彈出被適當地放置(目標以上和水平居中)。例如,在沒有鼠標事件的情況下,Angular 2中是否可以從元素中獲取樣式屬性?理想情況下,當彈出窗口出現時,維度被分配給一個變量。

回答

0

你爲什麼不只是使用基本的JavaScript訪問DOM元素的寬度和高度屬性,像這樣:

的Javascript:

getPopupDimentions() { 
    let myElement = getElementById("myPopup"); 
    return { 
     width: myElement.style.width, 
     height: myElement.style.height 
    } 
} 

HTML:

<div [style.left.px]="xCoord" [style.top.px]="yCoord" class="popup" id="myPopup"> 
    ... 
</div> 

當然,我上面發佈的Javascript需要在popup ha彈出後調用已經啓動。


如果你想更喜歡的方式,我會建議使用一個視圖孩子,像這樣:

的Javascript:

確保導入ViewChild import { Component, ViewChild } from '@angular/core'

@ViewChild('mypopup') mypopup; 

getPopupDimentions() { 
    return { 
     width: this.mypopup.nativeElement.style.width, 
     height: this.mypopup.nativeElement.style.height 
    } 
} 

HTML:

<div [style.left.px]="xCoord" [style.top.px]="yCoord" class="popup" #mypopup> 
    ... 
</div> 

如果您想了解更多關於角視圖的孩子,我建議檢查出this question and its answers