【问题标题】:Infinite scroll with appending elements angular2带有附加元素的无限滚动 angular2
【发布时间】:2017-09-19 20:59:50
【问题描述】:

我想实现无限滚动,其关键特性是可以添加新元素而不是实现列表的全部内容。

目前我尝试使用ng-infinite-scroll,但由于使用ngFor,它每次都会从头开始呈现整个列表。

<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>    

这种方法导致元素获取其数据(导致不可接受的延迟)。我想如果在路由器模块中使用子组件来实现这样的事情是否可以实现(但这听起来很糟糕,因为我没有有限的帖子列表)。

有人知道如何添加新元素而不重复已经渲染的元素吗?

【问题讨论】:

    标签: angular typescript infinite-scroll


    【解决方案1】:

    创建无限滚动的一种方法如下。

    1 - 将滚动事件添加到目标 div。 (跟踪滚动事件,并在满足条件时创建一个帖子组件。) 2 - 在 div 中添加 ng-template(在 DOM 中注入模板)

    HTML

    <div style="width: 750px;">
       <div class="posts-list"(scroll)="onScroll($event)">
          <ng-template #post></ng-template>
       </div>
    </div> 
    

    在您的 ts 文件中,添加一个函数,该函数将在您滚动时根据条件动态创建组件(例如,目标 div 的 80%)

    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;
    }
    

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 2012-02-29
      • 2017-08-06
      • 2017-05-02
      • 2015-09-18
      • 1970-01-01
      • 2018-11-09
      • 2015-02-11
      • 1970-01-01
      相关资源
      最近更新 更多