【问题标题】:angular 8 array change in console but not in view控制台中的角度 8 数组更改但不在视图中
【发布时间】:2019-08-15 20:35:49
【问题描述】:

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

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

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

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 视图没有更新,但控制台更新了?

【问题讨论】:

  • 这还不清楚。请发布所有相关代码,并准确说明您在做什么,您期望发生什么预期输出,在控制台的视图中)和实际输出(在视图和控制台中)。 Stackblitz 是你的朋友。
  • 我添加了更多信息,希望它能够更好地清除一些东西

标签: arrays angular ngfor


【解决方案1】:

视图循环遍历pager 的元素,并显示每个元素的索引。并且每当您单击时,您会更改 pager 的 elements,但 pager 仍然是一个包含 10 个元素的数组,因此索引仍然从 0 到 9。

您需要显示数组的元素,而不是其索引

【讨论】:

  • 非常感谢。下次我会更好地注意到这些东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-05
相关资源
最近更新 更多