Menu item currently unavailable

I am looking to disable the selected item menu when it is clicked until there is no response. I am curious if there is a universal way to achieve this.

For example:

<ng-template [ngIf]="item.hasSidebar">
      <li [hidden]="itemHidden(item.keyPage) || !item.visible" class="nav-item">
        <a class="nav-link" (click)="reloadSidebar(item)" style="cursor: pointer">
            <i class="nav-icon {{item.icon}}"></i> {{item.name | translate}} <i class="nav-change-sidebar fa fa-angle-right"></i>
            <span *ngIf="item.badge" [ngClass]="'badge badge-' + item.badge.variant">{{ item.badge.text }}</span>
        </a>
      </li>
    </ng-template>

The responses from each service are contained within the components, making it difficult for me to view them from the menu component itself.

Answer №1

To implement a toggleable flag in either the component or template accessible service, you must bind the [disabled] property to it like so:

<a class="nav-link" [disabled]="inProgress" (click)="reloadSidebar(item)" style="cursor: pointer">

Then, within the component code:

inProgress:boolean;

reloadSidebar(item){
   inProgress=true;

   ....perform necessary tasks

   inProgress=false; //usually in an asynchronous callback upon receiving the result

}

Answer №2

To simplify the process, consider introducing a variable status (for instance) that can encompass 2 or 3 states based on your requirements: ready, loading, and finish.

Initially, set the value of status to ready. When calling your function, transition it from ready to loading, and finally to finish at the end of the function.

Example :

example.ts

state: 'ready' | 'loading' | 'finish' = 'ready';
…
myFunction(item: any) {
  this.state = 'ready';
  this.myService.anOtherFunction(item).subscribe(() => {
    this.state = 'loading';
    console.log('it is loading time !);
  }
  this.state = 'finish';
  console.log('finished !);
}

example.html

<a class="nav-link" [disabled]="state === 'loading'" (click)="myFunction(item)" style="cursor: pointer">

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

Issue with rest operator behavior in TypeScript when targeting es2018

This specific code snippet functions properly in the TypeScript Playground... class Foo { constructor(...args: any[]) { } static make(...args: any[]): Foo { return new Foo(...args); } } Example However, when trying to incorpora ...

What are the appropriate token classifications for Dependency Injection (DI)?

Back in the days of Angular 1, providers only accepted strings as tokens. However, with the introduction of Angular 2, it seems that class tokens are now being predominantly used in examples. Take for instance: class Car {} var injector = ResolveInjector ...

What is the reason behind the input value becoming empty after a reset?

Currently, I am working with an input element reference: @ViewChild("inputSearch", { static: false }) This is how the template looks like: <input tabindex="0" type="text" (keydown)="keydownInputSearch($event)" #inputSearch autocomplete="off" ...

How to retrieve a Typescript variable within an ngIf conditional statement in Angular

How can I access a TypeScript variable inside an ngIf statement? TS: public data: string; HTML: <td> <div *ngIf="data === 'BALL' ; else noplay" >{{ play }}</div> <ng-template #noplay> {{ gotohome ...

What potential drawbacks come with utilizing the OOP approach in both JavaScript and React?

While working on an internal project, I found myself creating a base system and implementing a custom form structure using TypeScript with an OOP approach. class Form extends React.Component {} abstract class FormElement extends React.Component<{valid ...

Using Typescript to reduce an array of objects results in concatenation

In my quest to calculate the sum of integers from an array of objects stored in a redux slice, I have encountered a challenge. Here is the code snippet in question: export type Expense = { id: string; title: string; amount: number; date: st ...

When triggering the event: Was anticipating a spy, however received a Function instead

Upon running my test, I encountered the following error message: Error: Unhandled Promise rejection: <toHaveBeenCalledWith> : Expected a spy, but received Function. it('should change the value of myComponent', () => { spyOn(component ...

When trying to run ionic serve, I encountered the following error: "[ERROR] ng has unexpectedly closed with an exit code of 127."

My attempt to launch an ionic app on my Mac has hit a roadblock. While running npm install for the dependencies, everything goes smoothly without any issues. However, when I try to run 'ionic serve' or 'ionic s', an error crops up: [ng] ...

Issue with ion-select default value not being applied

In my ion-select element, I have multiple options and I want to set a default value based on the CurrentNumber when the view is loaded. Here's the code snippet: <ion-select formControlName="Level"> <ion-option [value]="level.id" *n ...

Exploring Angular 2 Paper-Input for Effective Form Management

I've been working on implementing Ng2 FormBuilder with paper-inputs and have successfully managed to get the bindings and validation up and running. You can check out my progress here: https://plnkr.co/edit/tr1wYZFyrn4uAzssn5Zs?p=preview <paper-i ...

How to fetch JSON data from a URL in Angular 2

let headers = new Headers(); headers.append('Content-Type', 'application/x-www-form-urlencoded'); let ep = './data.json'; this.events = this.http .get(ep, { headers: headers }) .map(res => res.json()) .map(({results}: ...

Encountering a CORS error in my Angular application while attempting to access a locally hosted Node Express API

I've been struggling with a CORS issue and can't seem to find a solution. My Node API application was built using Express, and the consumer is a simple Angular application. I've tried various solutions such as using CORS and including header ...

Switch app engines in real-time based on the URL path with express framework

How can I dynamically set App Engine based on the URL? In my application, I have two render engines available: serverSideRenderEngine & browserRenderEngine If the URL is /home, the app.engine should be set as serverSideRenderEngine If the URL is /l ...

Observing the completion of a subscriber function

Is there a more streamlined way to determine if the subscriber has finished executing or return something and catch it up-stream? Consider the following code snippets: this._subscriptions.push(this._client .getCommandStream(this._command) // R ...

Can TypeScript interfaces be used to achieve the same functionality as an abstract class?

I am currently working on developing a function that will return an array type with custom methods, allowing me to utilize it across various sections of the application. Typically, this is achieved using Abstract Classes where abstract methods are defined ...

Is it achievable to have a Dynamic Angular Output?

With multiple parent components needing a common child component that can dynamically and automatically adapt to each case, I am faced with the challenge of generating buttons using a forEach loop with data provided by the parent component (such as name, C ...

Creating nested namespaces with interfaces in Typescript type definitions

In my Javascript project, I am trying to define typing for a specific structure. Consider the following simplified example: a | + A.js + b | + B.js Here we have a folder 'a', and inside it there is another folder 'b'. My goal is t ...

Using Vue and TypeScript to define components

Whenever I attempt to install vue-class-component, vue-class-component, or vue-property-decorator, I encounter the following error message: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a ...

Using Typescript and Next.js to handle error messages returned from Axios responses

My Next.js application makes an API call to validate a registration form. The server returns error messages in the following format: {"message":"The given data was invalid.","errors":{"email":["The email has alr ...

Unnecessary Attributes in Type that Should be Automatically Inherited by Child Component

Within my child component, I am creating the Props interface and incorporating it into the React.Component. These Props must then be passed from the parent component to the child component. So far, everything is clear and logical. However, when I extend ...