2017-07-31 68 views
1

我使用角2爲我的項目之一。我有3個表的高度是未知的,即它可以grow.Now滾動,我想知道是否頂部該元件已通過頂部導航欄即,如果第一表滾動和第二是可見的,我需要初始化變量,這樣我可以做進一步的operations.I使用viewchild作爲角2從頂部滾動的距離基於ID

@ViewChild('leaveApproval') element:ElementRef; 
console.log(this.element.nativeElement.topOffset); 

和在html

試過
<div class="twelve wide right floated column" #leaveApproval> 

但console.log總是返回「undefined」。我該如何解決這個問題或者如何解決這個問題o走這個

+1

請提供一個Plunker示例。從提供的信息來看,目前還不清楚問題是什麼。 –

回答

0

您正在使用錯誤的屬性。正確的是this.element.nativeElement.offsetTop


UPDATE:

這裏是你如何能得到的活動表,並相應地進行進一步的操作:

  1. 假設你頂部導航欄有ID navBar,獲取navBar元素:

    @ViewChild('navBar') navBar: ElementRef;

  2. 獲取表,讓同IDS tableOnetableTwo說:

    @ViewChild('tableOne') tableOne: ElementRef; 
    @ViewChild('tableTwo') tableTwo: ElementRef; 
    
  3. 這裏是一個將返回可見表引用的函數:

    getVisibleTable(): ElementRef 
    { 
        let visibleTable: ElementRef = null; 
        const navBarHeight = this.navBar.nativeElement.height; 
        const tableOneTopOffset = this.tableOne.nativeElement.offsetTop; 
        const tableTwoTopOffset = this.tableOne.nativeElement.offsetTop; 
    
        if (tableOneTopOffset >= navBarHeight) 
        { 
         visibleTable = this.tableOne; 
        } 
        else if (tableOneTopOffset < navBarHeight) 
        { 
         if (tableTwoTopOffset >= navBarHeight) 
         { 
          visibleTable = this.tableTwo; 
         } 
         else 
         { 
          visibleTable = null; 
         } 
        } 
    
        return visibleTable; 
    } 
    
+0

該死的..這是我的愚蠢..感謝很多..答案我的問題的一半。請回答如何知道元素是否已通過元素的頂部,以便答案可以接受 –

+0

這應該很容易如果你認爲並應用thr正確的邏輯:)取頂部元素引用並獲取當前元素引用,其他應該很簡單,如果其他... – Faisal

+1

是的,沒錯。我明白,但它的其他人在未來閱讀本文:) –