Activate the button exclusively upon meeting the specified condition in Angular

I am facing an issue where the button remains disabled even after the correct condition is met for a certain range of values in a separate input.

The main goal is to prevent users from clicking the button if they enter incorrect data in the input field and proceed directly to the button without being prompted to correct the number of passengers entered.

Here is the HTML code snippet:

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

In the component.ts file:

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

If anyone can provide insights on what I might be missing or doing wrong, it would be greatly appreciated!

Answer №1

The requirement should be OR, not AND. The value of the numberOfPassengers variable cannot be both less than or equal to zero and greater than 9 at the same time. It can either be less than or equal to zero OR greater than 9.

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

However, you can eliminate the need for this function and the a tag. You can simply bind the routerLink in the button element and directly evaluate the condition in the template

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Testing an action within an interval in Angular using Jasmine

Looking to run a jasmine test on this method: public init(): Subscription { return interval(100).subscribe(() => this.doSomething()) } The goal is to verify that the doSomething method gets executed when the init function is called. We are usi ...

Encrypt and decrypt your store with ngrx-store-localstorage

I am attempting to encrypt data stored using ngrx-store-localstorage, following the instructions provided in the documentation: import { ActionReducer, MetaReducer } from '@ngrx/store'; import { localStorageSync } from 'ngrx-store-localstor ...

I have to deserialize a C# dictionary serialized in JSON and integrate it into my Angular 6 website using TypeScript

Utilizing an API, I receive a JSON string that I aim to deserialize within my Angular 6 website. Due to my unfamiliarity with how dictionaries function in TypeScript, I tend to steer clear of them when dealing with API responses. Upon executing the follo ...

Displaying Typescript command line options during the build process in Visual Studio

As I delve into the world of VS 2015 Typescript projects, I find myself faced with a myriad of build options. Many times, the questions and answers on Stack Overflow mention command line options that I'm not completely familiar with, especially when i ...

Avoid stopping Bootstrap Vue's events

Need help with a b-form-select control in Bootstrap Vue. Trying to execute a function when the value changes, but want the option to cancel the event and keep the original value. Complicating matters, the select is in a child component while the function ...

Troubleshoot: Issue with injecting external component into another component using directive in Angular 2

I need the child component template to be loaded into the parent component template. (calling them child and parent for simplicity) Here is the child component: import {Component,Directive, ElementRef, Input} from '@angular/core'; import {IONIC ...

How can I properly prevent the use of a nested observable subscription within a loop?

Utilizing Angular2 along with Firebase through Angularfire2 to retrieve data from a Firebase Realtime Database, which essentially consists of a large JSON object. The current setup involves a polling system where polls are stored in a 'Polls' no ...

Discovering the method to access a local function within a static function in Javascript ES6 (ES2015) or Typescript

Is there a way to access the non-static "foo2" method from inside the static "bar" method? So far, I'm only able to access the "foo1" and "foo3" methods. Can anyone provide guidance on how to achieve this? let foo1 = () => { alert('foo1� ...

What could be the reason behind lodash now classifying a mongoose object ID as empty when it previously did not?

Consider this scenario: const objId = new mongoose.Types.ObjectId('id goes here'); if (_.isEmpty(objId)) { throw new Error('an error is thrown here'); } I recently executed the code above and it got me thinking – is this a re ...

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

Issue: Unable to link to 'options' as it is not recognized as a valid attribute of 'chart'

Here is a sample component code snippet: import { Component, OnInit, Input } from '@angular/core'; import { Observable } from 'rxjs/Rx'; @Component({ selector: 'chart', templateUrl: 'app/comps/chart.html', ...

ERROR: Issue detected in the e class under the e_Host - inline template 0:0

As I was upgrading my angular2 project to RC5, a major issue surfaced. Despite reducing all the code to its minimum in order to debug the problem, I couldn't pinpoint its origin. Every request made by my app led to the following error message (as seen ...

Analyzing a Typescript project using SonarQube Scanner on a Mac OS slave in Jenkins: A step-by-step guide

My current task involves examining a TypeScript project on Jenkins using the SonarQube Scanner plugin on a Mac OS slave. Software: Jenkins (version 2.32.1) SonarQube Scanner for Jenkins plug-in (version 2.5) SonarQube Scanner (version 2.8) SSH slave plu ...

Utilizing Angular to link the model and showcase the information

I've recently integrated two models within my project. These models are interrelated and I'm looking to extract data from the comment section. The issue arises when I try to display the user's name using the HTML code @{{comment.user?.name}} ...

Updating objects in state dynamically

I have a form with multiple pages and I want to dynamically update the values obtained from it. To achieve this, I created a state variable called endResult which is initialized as an object with empty strings for each desired element. To illustrate, here ...

Creating an Event Listener for a Published Angular Elements Web Component

Note: The Web Component mentioned here is exported from Angular using Angular Elements and differs from traditional Angular components Experimenting with Angular Elements led to the creation of an NgFor component that loads the JSON file provided below. ...

The specified type 'X' cannot be used in place of type 'Y' in Typescript generics

Check out this code snippet: interface DummyTableRow { id: number; name: string; } interface RowChange<Row extends object> { newRow: Row | null; oldRow: Row | null; } interface RowChangeBag { Dummy: RowChangeList<DummyTableRow ...

What exactly does ngDefaultControl mean within the framework of Angular?

Hey there! This question is not a duplicate, I assure you. The issue at hand involves adding a certain directive to a tag that already contains the [(ngModel)] directive but is not nested within a form element. Without this additional directive, an error p ...

Harnessing the power of config data within the forRoot function

I'm currently struggling with implementing the forRoot method in my application. Within my app, I am setting up the databaseService in the ngOnInit function of the AppComponent: this.databaseService.addDatabaseData(databaseData); I believe it would ...

Retrieve request body/header variables in JWT strategy using Nest JS

Is there a way to retrieve the header variables or request body in a strategy? The JWT structure within the JwtStrategy currently appears as follows: @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor( private re ...