仅当 Angular 中的条件为真时启用按钮

Enable button only when condition is true in Angular

我试图让按钮仅在将特定范围的值输入单独的输入时才可用,但即使满足正确的条件,它也会保持禁用状态。

想法是阻止用户点击按钮,以防他在输入中输入错误数据并直接转到按钮 - 在这种情况下,不会提示他应该更正乘客人数.

HTML:

  <input type="number" id="passengers" [(ngModel)]="numberOfPassengers" (change)="checkValue()"> 
  <a routerLink="/summary"> <button [disabled]="checkButton()" (click)="saving()">To summary</button></a>

COMPONENT.TS

 ngOnInit() {
   this.buttonDisabled = true
  }

          public numberOfPassengers: number;
          public errorMessage: string = "";
          public errorMessageSubmit: string = ""
          public buttonDisabled: boolean;

      checkButton() {
        if (this.numberOfPassengers <= 0 && this.numberOfPassengers > 9) {
          return true;
        } else {
          return false;
        }
      }

      checkValue() {
        if (this.numberOfPassengers <= 0) {
          this.errorMessage = "Choose at least 1 passenger";
          return (this.numberOfPassengers = 1);
        } else if (this.numberOfPassengers > 9) {
          this.errorMessage = "Maximum of 9 passengers is allowed";
          return (this.numberOfPassengers = 9);
        }
      }

我做错了什么?感谢您的任何建议!

条件应该是OR,而不是AND。 numberOfPassengers 变量永远不能小于或等于 0 并且同时大于 9。它要么小于等于 0,要么大于 9。

checkButton() {
  if (this.numberOfPassengers <= 0 || this.numberOfPassengers > 9) {
    return true;
  } else {
    return false;
  }
}

但是您不需要这个函数,也不需要 a 标签。您可以在按钮元素中绑定 routerLink 并直接检查模板中的条件

<button routerLink="/summary" [disabled]="numberOfPassengers <= 0 || numberOfPassengers > 9" (click)="saving()">To summary</button>