1

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!

1 Answer 1

4

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.