【问题标题】:Disable button on condition在条件下禁用按钮
【发布时间】:2021-08-31 08:59:48
【问题描述】:

我正在 Angular 中构建一个自定义分页组件,您只能按“上一个”和“下一个”。

我想在索引等于 1 时禁用“上一页”按钮,并在索引等于最后一页时禁用“下一页”按钮。尝试了一些我用三元运算符和 ng-if 读取的不同内容,但我无法让它工作。

这是我的分页组件:

    <div class="btn-group" role="group" aria-label="pagination buttons">
  <button mat-icon-button class="vorige-icon" aria-label="vorige icon" (click)="onPrevious()">
    <mat-icon>chevron_left</mat-icon>
  </button>
  <span>{{this.currentPage + 1}} / {{this.totalPages}}</span>
  <button mat-icon-button class="volgende-icon" aria-label="volgende icon" (click)="onNext()">
    <mat-icon>chevron_right</mat-icon>
  </button>
</div>

这是条件:

checkDisabled() {
    if (this.currentPage <= 1 || this.currentPage >= this.totalPages) {
      this.isDisabled = true;
    }

【问题讨论】:

  • 您是否曾经在任何地方使用过isDisabled 值?或致电checkDisabled
  • 目前没有,为了清楚起见,我留下了条件语句,但我删除了非工作代码。使用了 ng-if & [disabled] 但可能有一些语法错误

标签: javascript html angular typescript conditional-operator


【解决方案1】:

您需要为此使用[disabled] 属性

 <button mat-icon-button class="vorige-icon" aria-label="vorige icon" (click)="onPrevious()"  [disabled]="currentPage <= 1" >
    <mat-icon>chevron_left</mat-icon>
  </button>
 <button mat-icon-button class="volgende-icon" aria-label="volgende icon" (click)="onNext()" [disabled]="currentPage >= totalPages" >
    <mat-icon>chevron_right</mat-icon>
  </button>

【讨论】:

  • 谢谢,正是我想要的!
【解决方案2】:

在 HTML 中,我们直接使用 disabled 属性来禁用按钮。 在 Angular 中,我们需要将 [disabled] 绑定到原生禁用属性。

添加属性 onPreviousPage()

[disabled]="index === 1"

添加属性 onNextPage()

[disabled]="index === lastPage"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-14
    • 2013-01-27
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 2021-01-06
    相关资源
    最近更新 更多