1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.