首页 > 解决方案 > 控制台中的角度 8 数组更改但不在视图中

问题描述

你好社区我是角度的新手,我正在尝试用逻辑制作一个分页组件,此时我已成功在控制台中获得正确的数组,但在视图中它没有改变。

我能够正确地浏览页面,只有分页组件本身没有改变。 分页视图

当我浏览页面时得到的控制台:

pagination.component.ts:25 (10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
pagination.component.ts:25 (10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
pagination.component.ts:25 (10) [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
pagination.component.ts:25 (10) [4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
pagination.component.ts:25 (10) [4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

这是服务中的函数,它创建在控制台上正确显示但不在视图中显示的数组。

initialPagination(totalPages: number) {
    this.pagination = [];
    this.numberOfPages = totalPages
    if (this.numberOfPages <= 10) {
      // less than 10 total pages so show all
      this.startPage = 1;
      this.endPage = this.numberOfPages;
    } else {
      // more than 10 total pages so calculate start and end pages
      if (this.pageToShow <= 6) {
        this.startPage = 1;
        this.endPage = 10;
      } else if (this.pageToShow + 4 >= this.numberOfPages) {
        this.startPage = this.numberOfPages - 9;
        this.endPage = this.numberOfPages;
      } else {
        this.startPage = this.pageToShow - 5;
        this.endPage = this.pageToShow + 4;
      }
    }

    // create an array of pages to ng-repeat in the pager control
    for (let i = this.startPage; i < this.endPage + 1; i++) {
      this.pagination.push(i)
    }
    return this.pagination
}

这里是组件本身

<ul class="pagination">
<li (click)="replacePage(pagination.pageToShow - 1)"><a>&laquo;</a></li>
<li (click)="replacePage(i)" [ngClass]="{active:pagination.pageToShow === i}"
    *ngFor="let page of pager; let i = index"><a>{{i + 1}}</a></li>
<li (click)="replacePage(pagination.pageToShow + 1)"><a>&raquo;</a></li>

这是分页的初始化:

  replacePage(page: number) {
    if (page >= 0) {
      if (page < this.numberOfPages) {
        this.pagination.pageToShow = page;
        this.pager = this.pagination.initialPagination(this.numberOfPages)
        console.log(this.pager)
      }
    }
  }

为什么 iis 视图不更新但控制台更新?

标签: arraysangularngfor

解决方案


The view loops through the elements of pager, and displays the index of each element. And whenever you click, you change the elements of pager, but pager is still an array of 10 elements, with indices thus still going from 0 to 9.

You need to display the elements of the array, rather than its indices.


推荐阅读