Table of Contents
Preface
Requirements
Analysis
Code
scroll-table.component.html
scroll-table.component.ts
scroll-table.component.scss
Summary and Thoughts
Home Web Front-end JS Tutorial Analysis of encapsulation of scrolling list component in Angular 6

Analysis of encapsulation of scrolling list component in Angular 6

Jul 23, 2018 am 11:35 AM
angular javascript

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

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

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Angular components and their display properties: understanding non-block default values Angular components and their display properties: understanding non-block default values Mar 15, 2024 pm 04:51 PM

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.

See all articles