首页 > 解决方案 > 如果月份无效,则启用/禁用按钮

问题描述

我正在尝试创建几个月/年的导航。

如果用户在月份,我想禁用left箭头导航按钮,如果用户在Jan月份,我想禁用右导航按钮Dec

下面是我的代码

  ngOnInit() {
    this.year = new Date().getFullYear();
    this.monthIndex = new Date().getMonth();
  }

浏览月份

下面是我的代码,

  navigationArrowMonth(flag) {
    this.monthNavigatorValidation(flag)
  }

  monthNavigatorValidation(flag?) {
    if(flag) {
      if(this.monthIndex < 0 || this.monthIndex >= 11) {
        this.isRightMonthDisabled = true;
        return false;
      } else {
        this.monthIndex = this.monthIndex + 1;
        this.isRightMonthDisabled = false;
        return true;
      }
    } else {
      if(this.monthIndex < 0 || this.monthIndex <= 11) { 
        this.isLeftMonthDisabled = true;
        return false;
      } else {
        this.monthIndex = this.monthIndex - 1;
        this.isLeftMonthDisabled = false;
        return true; 
      }

    }
  }

HTML 模板

 <!--Month navigation-->

                <!-- 
                    On click should call navigationArrowMonth
                -->
                <button [disabled]="isLeftMonthDisabled" (click)="navigationArrowMonth(0)" mat-icon-button id="leftMonthKey" aria-label="left naviage">
                    <mat-icon>keyboard_arrow_left
                    </mat-icon>
                </button>

                <div id="monthValue" class="nameArrage" style="width: 120px;">
                    <!-- 
                        Display month in Alphabets
                    -->
                    {{months[monthIndex]}}
                </div>

                <!-- 
                    On click should call navigationArrowMonth
                    disable when limit reached
                -->
                <button [disabled]="isRightMonthDisabled" (click)="navigationArrowMonth(1)" mat-icon-button id="rightMonthKey" aria-label="right naviage">
                    <mat-icon>keyboard_arrow_right
                    </mat-icon>
                </button>

                <!--Month navigation end-->

但是我的代码没有按预期工作,

我在这里做错了什么?

标签: javascriptangulartypescript

解决方案


这个更简单的解决方案

app.component.html
<h2>{{monthIndex}}</h2>

<div>
  <button 
    type="button" 
    [disabled]="monthIndex <= 0"
    (click)="onMove(-1)"
    >
    LEFT
  </button>
  <button 
    type="button" 
    [disabled]="monthIndex >= 11"
    (click)="onMove(1)"
    >
    RIGHT
  </button>
</div>

app.component.ts
year: number;
  monthIndex: number;


  ngOnInit() {
    this.year = new Date().getFullYear();
    this.monthIndex = new Date().getMonth();
  }

  onMove(move: number): void {
    this.monthIndex += move;
  }

推荐阅读