我创建了一个基本组件,它提供了一个标志wasoOnce,如果组件完全位于视图内或其上边缘已到达视图的上边缘,则该组件将变为真。
@Injectable()
export class AppearOnce implements AfterViewInit, OnDestroy {
appearedOnce: boolean;
elementPos: number;
elementHeight: number;
scrollPos: number;
windowHeight: number;
subscriptionScroll: Subscription;
subscriptionResize: Subscription;
constructor(private element: ElementRef, private cdRef: ChangeDetectorRef){}
onResize() {
this.elementPos = this.getOffsetTop(this.element.nativeElement);
this.elementHeight = this.element.nativeElement.clientHeight;
this.checkVisibility();
}
onScroll() {
this.scrollPos = window.scrollY;
this.windowHeight = window.innerHeight;
this.checkVisibility();
}
getOffsetTop(element: any){
let offsetTop = element.offsetTop || 0;
if(element.offsetParent){
offsetTop += this.getOffsetTop(element.offsetParent);
}
return offsetTop;
}
checkVisibility(){
if(!this.appearedOnce){
if(this.scrollPos >= this.elementPos || (this.scrollPos + this.windowHeight) >= (this.elementPos + this.elementHeight)){
this.appearedOnce = true;
this.unsubscribe();
this.cdRef.detectChanges();
}
}
}
subscribe(){
this.subscriptionScroll = Observable.fromEvent(window, 'scroll').startWith(null)
.subscribe(() => this.onScroll());
this.subscriptionResize = Observable.fromEvent(window, 'resize').startWith(null)
.subscribe(() => this.onResize());
}
unsubscribe(){
if(this.subscriptionScroll){
this.subscriptionScroll.unsubscribe();
}
if(this.subscriptionResize){
this.subscriptionResize.unsubscribe();
}
}
ngAfterViewInit(){
this.subscribe();
}
ngOnDestroy(){
this.unsubscribe();
}
}
您可以简单地扩展这个组件,并通过继承
@Component({
template: `
<div>
<div *ngIf="appearedOnce">...</div>
...
</div>
`
})
class MyComponent extends AppearOnceComponent {
...
}
利用appearedOnce财产记住调用超()如果你需要重写构造函数或lifecyclehooks。
(编辑)plunker: https://embed.plnkr.co/yIpA1mI1b9kVoEXGy6Hh/
(编辑)我已经变成了下面另一个答案一个指令这一点。
不知道,但可以在这个环节是有帮助的https://angular.io /docs/ts/latest/guide/animations.html#!#parallel-animation-groups? – sandyJoshi
嗨桑迪,我确实看了看,并行动画组的方法有助于链动画,但它似乎没有办法触发当div进入视点后滚动到页面的低点可能发生在当使用决定向下滚动到div时的可变时间。你知道这个UI行为的任何解决方案吗? – Ultronn