2016-11-14 109 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