2016-11-14 64 views
2

我只想證明我的ion-header當頁面滾動到特定點ionic2 - 滾動觸發

HTML

<ion-header *ngIf="headered"><!--use ngif to trigger--> 
    <ion-navbar> 
    some content 
    </ion-navbar> 
</ion-header> 

所以這將是通過滾動觸發:

TS

import { ..., Content } from 'ionic-angular'; 

... 
@ViewChild(Content) content:Content; 

headered = false; 
... 
ngAfterViewInit() { 
    this.content.addScrollListener(this.onPageScroll); 
} 

onPageScroll(event) { 
    console.log(event.target.scrollTop); 
    if(event.target.scrollTop > 640){ 
     this.headered = true; 
     console.log(this.headered);///<-- this did trigger when scroll more than 640 
    }else{ 
     this.headered = false; 
    } 
} 

我在控制檯上得到了true,但沒有顯示標題。我再次通過添加一個按鈕調用這個函數來測試它:

toggleHeader(){ 
    this.headered = (this.headered == false) ? true : false; 
} 

並且頭部確實顯示和隱藏了。

爲什麼scroll事件不能顯示標題?我該如何解決這個問題?

Update01

我想:

scrollCount = 0; 

... 

onPageScroll(event) { 
    this.scrollCount = event.target.scrollTop; 
console.log(this.scrollCount);///<-- this give me reading 
} 

///then use ngDoCheck to detect: 

ngDoCheck(){ 
console.log(this.scrollCount);///<-- this always get 0. 
} 

正如你可以看到裏面onPageScroll()我得到讀書出來的,我沒有。我懷疑它與@ViewChild(Content) content:Content;有關,ionic2建議在their doc

回答

0

就像你說的,考慮看看Content - Ionic Docs我發現:

resize()

Tell the content to recalculate its dimensions. This should be called after dynamically adding headers, footers, or tabs.

所以,既然你做

@ViewChild(Content) content:Content;

與嘗試獲取內容的實例如下:

onPageScroll(event) { 
    console.log(event.target.scrollTop); 
    if(event.target.scrollTop > 640){ 
     this.headered = true; 
     console.log(this.headered);///<-- this did trigger when scroll more than 640 
    }else{ 
     this.headered = false; 
    } 

    // Update the content since the header was shown/hidden 
    this.content.resize(); 
} 

EDIT

由於onPageScroll被稱爲很多次,你只需要當scrollTop高於640 沒有被示出的報頭(或更新內容時scrollTop低於或等於比正在顯示640 頭)讓我們改變代碼一點點:

onPageScroll(event) { 
    console.log(event.target.scrollTop); 
    if(event.target.scrollTop > 640 && !this.headered){ 
     // If the scrollTop is higher than 640 and the header is hidden, we need to show it (this prevent trying to update the header status also when scrollTop is 642, 643, and so on 
     this.headered = true; 
     console.log(this.headered);///<-- this did trigger when scroll more than 640 

     if(this.content) { 
     // Update the content 
     this.content.resize(); 
     } 
    }else if(event.target.scrollTop <= 640 && this.headered){ 
     // If the scrollTop is lower or equal than 640 and the header is visible, we need to hide it (this prevent trying to update the header status also when scrollTop is 639, 638, and so on 
     this.headered = false; 

     if(this.content) { 
     // Update the content 
     this.content.resize(); 
     } 
    } 
} 
+1

我想你的方法沒有奏效。請看看我的更新。 – sooon

+0

我已經更新了答案。請讓我知道'resize()'方法是否有用。 – sebaferreras

+0

錯誤:'無法讀取未定義的屬性'調整大小'。 – sooon