Reputation: 92
I would like to implement infinite scroll whose key feature is possibility to add new elements instead actualising whole content of list.
Currently I try with ng-infinite-scroll
but as a result of using ngFor
it every time renders whole list from the beginning.
<div style="width: 750px;">
<div class="posts-list"
infinite-scroll
[infiniteScrollDistance]="2"
[infiniteScrollThrottle]="300"
(scrolled)="onScrollDown()">
<post-component *ngFor="let item of array" [dataHref]="item"></post-component>
</div>
Such approach causing that elements fetch their data (what leads to unacceptable delays). I thought if it would be achievable to realize such thing with child components in router module (but this sounds bad because I don't have finite list of posts).
Anyone has ideas how to add new elements without repeating those which were already rendered?
Upvotes: 1
Views: 1492
Reputation: 709
One way to create infinite scrolling, is as following.
1 - Add scroll event to your target div. (to track scroll event, and create a post component when condition is met.) 2 - Add ng-template inside your div (to inject a template in DOM)
HTML
<div style="width: 750px;">
<div class="posts-list"(scroll)="onScroll($event)">
<ng-template #post></ng-template>
</div>
</div>
In your ts file, add a function that will create a component dynamically based on a condition when you have scroll (eg. 80% of your target div)
TS
@ViewChild('post') element: ElementRef;
constructor(private viewContainerRef: ViewContainerRef, private componentFactoryResolver: ComponentFactoryResolver){}
onScroll($event): void {
// apply condition eg. when 80 % of div is scrolled
if(conditionIsMet){
this.loadPostComponent();
}
}
loadPostComponent() {
let postComponent = this.componentFactoryResolver.resolveComponentFactory(PostComponent);
let componentRef = this.element.createComponent(postComponent);
(<PostComponent>componentRef.instance).data = post.data;
}
Hope that helps you.
Upvotes: 2