Angular: Enabling or Disabling a Button Based on a Conditional Statement

I currently have an if condition set up where if the API call returns 0, the button to proceed to the next page should be disabled. However, I am unsure of how to achieve this as you are not able to call a method within another method. Here is my current setup:

HTML:

<button type="button" class="primary-button mat-raised-button buttontxt" (click)="next()">Next</button>

TS:

 ngOnInit(): void {
    this.appService.showLoader(true);
    this.coachService.GetCategories().subscribe(res =>
     {
      if (res && res.length === 0){
          this.appService.openSnackBar('You do not have access to this Service');
         //This line is where I thought to call this method to disable the button
          this.next = [disabled];
          } else if (res && res.length === 1) {
            if( res[0].name === 'pageOne'){
               //irrelevant code          }
//Button

nextMindset(){
//route to pageOne
  }

Answer №1

To manage the accessibility of a feature, consider utilizing a control variable like disabled.

disabled: boolean = true;

ngOnInit(): void {
  this.appService.showLoader(true);
  this.coachService.GetCategories().subscribe(res => {
    if (res && res.length === 0){
      this.appService.openSnackBar('You do not have access to this Service');
      this.next = [disabled];
      this.disabled = true;
    } else if (res && res.length === 1) {
      this.disabled = false;
      if( res[0].name === 'pageOne'){
        //irrelevant code          
      }
    }
  }
}

next(){
  if (disabled) return;
  //navigate to pageOne
}

template

<button type="button"
  class=" primary-button mat-raised-button buttontxt"
  (click)="next()"
  [disabled]="disabled">Next</button>

Answer №2

HTML Code:

    <button type="button"
            class=" primary-button mat-raised-button buttontxt"
            (click)="next()"
            [disabled]="resLength"
    >Proceed</button>

TS Script:

    resLength = false;

    ngOnInit(): void {
    this.appService.showLoader(true);
    this.coachService.GetCategories().subscribe(res =>
     {

      resLength = !!res.length;

      if (res && res.length === 0){
          this.appService.openSnackBar('You do not have access to this Feature');
         //Disabling the button here
          this.next = [disabled];
       } else if (res && res.length === 1) {
            if( res[0].name === 'pageOne'){
               //irrelevant code          }
    
    //Button Click Function
    
    nextMindset(){
    //Navigate to pageOne
      }

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

Angular - Utilizing NgRx selector for efficient data update notifications

Is there a method to create a "data updated" indicator when I am not interested in the actual updated data itself? Consider a scenario with a reducer: const initialState: SomeReducer = { dataInQuestion: Array<SomeDto>, ... } Following an action ...

Having trouble getting Chutzpah to work with TypeScript references

I am currently working on a project where my project folder contains the following files: chai.d.ts chai.js mocha.d.ts mocha.js appTest.ts appTest.js chutzpah.json The chai and mocha files were acquired through bower and tsd. Let's take a look at ...

Rx.js struggles to access historical values

Seeking assistance with retrieving the last 3 values emitted. Despite using the provided code to populate uiOrder and invoking cancelOrderItem() multiple times, I am unable to access the last 3 revisions of the order via getHistory(). Instead, I receive th ...

Tips for targeting a specific element with providers in Ionic

By using the specified pattern, I am aiming to achieve a unique toolbar or header for only certain pages. Is there a way to accomplish this without injecting the provider and keeping the page as a standalone? My understanding of Ionic is still developing, ...

How can I properly send a file to express-fileupload using a post request in Angular 9?

I have successfully accomplished this task in Postman by following this link: https://i.sstatic.net/dKs8b.png However, when attempting to do the same in Angular, the functionality does not seem to be working. Below is the Angular code snippet: <input ...

The production build for Angular 9 Keyvalues pipe fails to compile

After successfully running my app on the development server with ng serve, I encountered a failure when trying to build it for production. The error message that popped up was: ERROR in src/app/leaderboard/leaderboard.component.html(9,17): Argument of typ ...

Eliminate duplicate dropdown options in Angular 2 using a filter function

Is there a way to filter reporting results in an Angular 2 dropdown list? I am currently attempting to do so within the *ngFor template but haven't had any success. I will also try using a custom pipe. The data is coming from a JSON array. Specificall ...

Developing a Gulp buildchain: Transforming Typescript with Babelify, Browserify, and Uglify

I've configured a buildchain in Gulp, but when I execute the gulp command, it only utilizes one of the two entry points I specify. My goal is to merge the methods outlined in these two resources: and here: https://gist.github.com/frasaleksander/4f7b ...

create a fresh variable instead of appending it to the current object

I'm encountering an issue where a new array is supposed to be added on callback using props, but instead an empty variable is being added. Here's the code snippet: const [data, setData] = useState({ title: "", serviceId: "", serviceNa ...

Encountered error: Unable to locate module - Path 'fs' not found in '/home/bassam/throwaway/chakra-ts/node_modules/dotenv/lib' within newly generated Chakra application

Started by creating the app using yarn create react-app chakra-ts --template @chakra-ui/typescript. Next, added dotenv with yarn add dotenv Inserted the following code block into App.tsx as per the instructions from dotenv documentation: import * as dote ...

Tips for incorporating a captcha image into your angular 8 application

I would like to implement a captcha element with an image of letters and an input field for the user, (I prefer not to use the "I am not a robot" version) similar to this example: https://i.sstatic.net/dd1Gb.png Is this feature still available today? ...

Monkey patching in Typescript cannot be applied to the String data type

I have developed a new interface for String that incorporates additional utility methods by utilizing Monkey-patching. interface String { toCamelCase(): string; } String.prototype.toCamelCase = function (): string { return this.replace(/[^a-z ]/gi, ...

Issues with connecting to server through Angular websocket communication

I deployed the server on an Amazon AWS virtual machine with a public IP address of 3.14.250.84. I attempted to access it using Angular frontend like so: public establishWebSocketConnection(port : number){ this.webSocket = new WebSocket('ws://3.14.250. ...

Invalid Argument: Cannot use an empty value with the AsyncPipe at invalidArgumentError

I'm facing an issue with extracting a string value from the Observable using the pipe and map operators. Despite my efforts, I always end up with an empty string as the result. I'm hoping that someone can assist me in understanding the cause of t ...

angular Struggling with @Input and data interpolation functionality within web components

I have built a collection of web components designed for various Angular projects. To make these components reusable, I am using @angular/elements to convert them into custom elements and then serving them via http-server. One of the components I develope ...

Having Issues with CDK Virtual Scrolling in Angular Material Table

Dealing with an angular material table that contains millions of records can be quite challenging. I have implemented pagination with various options such as 10, 25, 50, 100, 500, and 1000 items per page. However, when selecting the option for 1000 or all ...

Angular digit organization - adding a space between each grouping of a thousand

In the process of formatting numbers, I am encountering different scenarios - some are directly defined in the HTML template, while others are fetched using @ViewChild textContent in TS. The desired format is to display numbers like this: 1 213.00. Specif ...

What is the best way to determine the type of a key when using direct key access and a generic interface in TypeScript?

I've been trying to make TypeScript understand the types in this specific scenario: There are 2 interfaces defined as follows: interface A { first: string; } type B = { second: string; } In addition, there is a generic interface with 2 mappers ...

The value calculated by Auto does not display as a valid number in Angular 8 until it has been manually edited

Having an issue with a form submission for invoicing. The total value field, which is auto-calculated based on quantity and unit price, does not show up as numeric data in the backend onSubmit event unless I manually interact with it by adding something ...

What is the process for deciphering HTML elements in TypeScript?

I am currently utilizing Angular 2 alongside C# and SQL Server for my project. One of the scenarios I'm facing involves retrieving an HTML string from the database, which may contain encoded HTML tags or special characters such as (> , <, &, ...