我創建了一個基本組件,它提供了一個標誌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