Home > Web Front-end > JS Tutorial > body text

Analysis of encapsulation of scrolling list component in Angular 6

不言
Release: 2018-07-23 11:35:58
Original
1850 people have browsed it

The content shared with you in this article is about the analysis of the encapsulation of the scrolling list component in Angular 6. It has certain reference value. Friends in need can refer to it.

Preface

Learning should be a process of combining input and output. This is the reason for writing this article.
In large screen display web APP, scrolling lists are often used. After several attempts, I settled on a pretty good idea.

Requirements

  • The thead part of the list header is static, while the tbody part scrolls upward.

  • After the body part is scrolled, the data needs to be refreshed. The final effect is to display all relevant data in the database in an upward scrolling form.

Analysis

If the amount of data is relatively small, we can take out all the data at once and put it into the DOM for circular scrolling. In fact, it is similar to the effect of a carousel.

But if there is a lot of data, doing so may cause a memory leak. Naturally, we can think of paginating the list data. My initial idea is to put a p as a container on the outer layer of table, and then table periodically increases the top value, etc. table Halfway through the run, request data from the backend, dynamically create a component tbody and insert it into table, and then wait for the previous tbodyWhen you finish walking (out of sight), delete this component. The idea seemed feasible, but it ran into trouble in practice. When deleting the previous component, the height of table will be reduced, and the table will instantly fall down. This is obviously not what we want, and the side effects are quite serious.

In this case, I separated tbody into two table, and the two table loops. When there is no data under the previous table, the second table starts to walk, and waits for the first table to completely walk outp , reset its position to below p, update the data, and then repeat the actions in between. It’s a little troublesome to complete, but the effect is passable and satisfactory. The problem is that the two timers are unstable. When I open other software and come back, the two tables run inconsistently. For this congenital disease, setInterval is not accurate enough, and the two timers are prone to poor coordination.

Finally, on the way home from get off work, I thought of a method that didn't require two tables. Use only one table to move up regularly. When halfway through, clear the timer, reset the position, and update half of the data. That is to say, the first half of the data in the array is removed, and the new data pulled from the background is spliced ​​onto the array. In this way, the data can be continuously refreshed, and table looks like it keeps going up.

Code

scroll-table.component.html

<p class="table-container">
  <table class="head-show">
    <thead>
      <tr>
        <th style="width:12.8%;">字段1</th>
        <th style="width:12.8%;">字段2</th>
        <th>字段3</th>
        <th style="width:12.8%;">字段4</th>
      </tr>
    </thead>
  </table>
  <p class="scroller-container">
    <table #scroller class="scroller">
      <tbody>
        <tr *ngFor="let ele of tbody">
          <td style="width:12.8%;">{{ele.field01}}</td>
          <td style="width:12.8%;">{{ele.field02}}</td>
          <td><p>{{ele.field03}}</p></td>
          <td style="width:12.8%;">{{ele.field04}}</td>
        </tr>
      </tbody>
    </table>
  </p>
</p>
Copy after login

scroll-table.component.ts

import { Component, OnInit, ViewChild, ElementRef, Input } from '@angular/core';
import { HttpService } from '../http.service';

@Component({
  selector: 'app-scroll-table',
  templateUrl: './scroll-table.component.html',
  styleUrls: ['./scroll-table.component.scss']
})
export class ScrollTableComponent implements OnInit {
  tbody: any = [];
  @Input() url; //将地址变成组件的一个参数,也就是输入属性
  //控制滚动的元素
  @ViewChild('scroller') scrollerRef: ElementRef;
  timer: any;

  freshData: any;

  pageNow = 1;//pageNow是当前数据的页码,初始化为1

  constructor(private http: HttpService) {}

  ngOnInit() {
    //初始化拿到native
    let scroller: HTMLElement = this.scrollerRef.nativeElement;
    this.http.sendRequest(this.url).subscribe((data :any[]) => {
      
      this.tbody = data.concat(data);
    });
    //开启定时器
    this.timer = this.go(scroller);
  }

  getFreshData() {
  //每次请求数据时,pageNow自增1
    this.http.sendRequest(`${this.url}?pageNow=${++this.pageNow}`).subscribe((data:any[]) => {
      if(data.length<10) {
        //数据丢弃,pageNow重置为1
        this.pageNow = 1;
      }
      this.freshData = data;
    });
  }
  
  go(scroller) {
    var
      moved = 0,
      step = -50,
      timer = null,
      task = () => {
        let style = document.defaultView.getComputedStyle(scroller, null);
        let top = parseInt(style.top, 10);
        if (moved < 10) {
          if(moved===0) {
            this.getFreshData();
          }
          scroller.style.transition = "top 0.5s ease";
          moved++;
          scroller.style.top = top + step + 'px';

        } else {
          //重置top,moved,清除定时器
          clearInterval(timer);
          moved = 0;
          scroller.style.transition = "none";
          scroller.style.top = '0px';
          //更新数据
          this.tbody = this.tbody.slice(10).concat(this.freshData);
          timer = setInterval(task,1000);
        }
      };
    timer = setInterval(task, 1000);
  }
}
Copy after login

scroll-table.component.scss

.table-container {
    width: 100%;
    height: 100%;
}
.head-show {
    border-top: 1px solid #4076b9;
    height: 11.7%;
}
.scroller-container {
    border-bottom: 1px solid #4076b9;
    //border: 1px solid #fff;
    width: 100%;
    //height: 88.3%;
    height: 250px;
    box-sizing: border-box;
    overflow: hidden;
    position:relative;
    .scroller {
        position: absolute;
        top:0;
        left:0;
        transition: top .5s ease;
    }
}
table {
    width: 100%;
    border-collapse: collapse;
    table-layout: fixed;
    //border-bottom:1px solid #4076b9;
    th {
        
        border-bottom:1px dashed #2d4f85;
        color:#10adda;
        padding:8px 2px;
        font-size: 14px;
    }
    td {
        border-bottom: 1px dashed #2d4f85;
        font-size: 12px;
        
        color:#10adda;
        position: relative;
        height: 49px;
        p{
            padding:0 2px;
            box-sizing: border-box;
            text-align:center;
            display: table-cell;
            overflow: hidden;
            vertical-align: middle;
        }
        //border-width:1px 0 ;
    }
}
Copy after login

The effect of this is that the component only needs to pass in one parameter url, and then all operations, including updating data, are completed by the component itself. This completes the component encapsulation and facilitates reuse.

Summary and Thoughts

1. Update data should be updated at the source, that is to say, do not add and delete DOM elements. This operation is troublesome and the performance is low. Putting it at the source means making a fuss about the array that stores the display data in the component class.
2. New data requested in the background should be prepared in advance and placed in another temporary array. It is equivalent to a cache and a temporary register.
3. I imagine the component as a function. It has only one parameter, which is the address of the data. As long as this parameter is present, the component can work normally and does not depend on any other value. Loose coupling.
4. Strengthen the idea of ​​functional programming. Although this is the characteristic of React, I always feel that angular can also be used.

Related recommendations:

How to set AngularJs custom directives and the naming convention of custom directives

##In AngularJs What is the relationship between model, Controller and View? (Pictures and text)

The above is the detailed content of Analysis of encapsulation of scrolling list component in Angular 6. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template