Angular 2分页控制与输入 - 验证

时间:2017-06-01 14:18:07

标签: angular pagination grid

我有一个分页组件。

enter image description here

HTML:             第一页         

    <button md-mini-fab (click)="previous()" [disabled]="isFirstpageButtonDisabled" style="margin:0 0.5rem">
        <md-icon>chevron_left</md-icon>
    </button>
    <input #input type="text" (keyup.enter)="goToPage(input.value)" [(value)]="pageIndex" style="margin:0 0.5rem; width: 40px;">
    / {{totalPages}}
    <button md-mini-fab (click)="next()" [disabled]="isLastpageButtonDisabled" style="margin:0 0.5rem">
        <md-icon>chevron_right</md-icon>
    </button>

    <button md-mini-fab (click)="goToPage(totalPages)" [disabled]="isLastpageButtonDisabled" style="margin:0 0.5rem">
        <md-icon>last_page</md-icon>
    </button>

当用户在输入框中输入无效的数字/字符时,我会显示错误消息。我还需要将输入框值恢复为之前有效的前一个数字。

checkPageIndex() {
    this.validpageIndex = true;    

    if (this.pageIndex < 1 || this.pageIndex > this.totalPages || isNaN(this.pageIndex)) {
        this.validpageIndex = false;
        this.toaster.showToaster('Please select a page between 1 and ' + this.totalPages + '.');
        return;
    }
}

我尝试通过保存上一页索引并在有效检查失败后分配该值来实现此目的:

this.pageIndex = this.previousPageIndex;

在控制台日志中正确获取此值,但输入文本框仍显示无效输入。我怎样才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

你走在正确的轨道上,只有几件事能让你到达那里。基本上,您希望在更改当前pageIndex时跟踪lastPageIndex,然后在检查失败时将当前pageIndex设置为lastPageIndex中的值。将输入更改为ngModel并为文本字段添加on blur事件以捕获其更改(如果它们离开)也不会有什么坏处。如果您的用户可能尝试将输入更改为其他无效的输入,您可以添加对这些输入的检查,甚至可以使用ngOnChanges()来监视输入。示例更新的goToPage函数可能看起来像

 goToPage(page: number) {
    // check to make sure number is valid
    if(this.pageIndex <= 1 || this.pageIndex >= this.pages.length || isNaN(this.pageIndex)) {
      alert("invalid page selected");
      this.pageIndex = this.lastPageIndex;
    }
    else {
      // update current page and save last index
      this.pageIndex = page;
      this.lastPageIndex = this.pageIndex;
    }
  }

这是一个简化的plunker,其中包含您的问题的工作示例http://plnkr.co/edit/EFBiVz4gy4nl4mFDe6x1?p=preview