Enable button only when condition is true in Angular

13,340

The condition should be OR, not AND. The numberOfPassengers variable can never be less than or equal to zero AND be greater than 9 simultaneously. It is either less than or equal to zero OR greater than 9.

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

But you don't need this function nor the a tag. You could bind the routerLink in the button element and directly check the condition in the template

<button routerLink="/summary" [disabled]="numberOfPassengers <= 0 || numberOfPassengers > 9" (click)="saving()">To summary</button>
Share:
13,340
JoseTurron
Author by

JoseTurron

Updated on June 04, 2022

Comments

  • JoseTurron
    JoseTurron about 2 years

    I'm trying to make the button only available when a certain range of values is put into a separate input but it stays disabled even if the correct condition is met.

    The idea is to stop the user from clicking the button in case he puts incorrect data in the input and goes directly to the button - in this situation, he won't be prompted that he should correct the number of passengers.

    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);
            }
          }
    

    What am I doing wrong? Thanks for any suggestions!