Angular 7 ngIf not displaying content after initial load issue

Check out this snippet of HTML code:

<form class="k-form-inline" [formGroup]="catalogForm" (ngSubmit)="onSubmit()" (keyup.enter)="onSubmit()">
     <button class="k-button k-primary" style="width:100px" [disabled]="loading" style="margin-right:15px" >
              <span class="k-icon k-i-zoom" style="padding-right: 20px"> </span>Search
     </button>
     <span *ngIf="loading" class="k-icon k-i-loading" style="font-size: 16px; padding-left:10px"></span>
</form>

This is the component part:

public loading : boolean = false;

onSubmit() {
    this.loading = true;
     this.Service.subscribe(res => {this.loading = false;})
}

Additionally, here is the service code snippet for you to review:

export class ProductService  extends BehaviorSubject<GridDataResult>{

constructor(private http: HttpClient) 
  { super(null); }

protected fetch(state: any, searchForm: ProductCatalogSearch,CustomerGroupCode : string): Observable<GridDataResult> {
    searchForm.CustomerGroupCode = CustomerGroupCode;
    return this.http
      .post<any>(this.rootURL + '/product/catalogsearch', searchForm)
      .pipe(
        map(response => (<GridDataResult>{
          data: response,
          total: (response as any[]).length
        }))
      );
  }

  public query(state: any, searchForm: ProductCatalogSearch, CustomerGroupCode: string): void {
    this.fetch(state, searchForm,CustomerGroupCode)
      .subscribe(x => super.next(x));
  }
}

Although the functionality works perfectly on the initial button click after a page load or refresh, subsequent clicks seem to deactivate it. The 'loading' variable does not update on subsequent clicks. Any ideas on what might be causing this issue?

Answer №1

Make sure to update the value of this.loading to false even if there is an error in the response:

submitForm() {
  this.loading = true;
  this.Service.subscribe(res => {
    this.loading = false;
  }, err => {
    this.loading = false;
  });
}

Answer №2

To improve angular's ability to detect changes in the loading variable, consider using the AfterViewChecked lifecycle hook in conjunction with detectChanges.

import { AfterViewChecked, ChangeDetectorRef, Component } from '@angular/core';
...
constructor(private cdref: ChangeDetectorRef)
...
ngAfterViewChecked(): void { this.cdref.detectChanges(); }

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

Steps for dynamically adding a link to images in React with TypeScript based on a condition

In my project, I am looking to dynamically add links to images based on certain conditions using JavaScript and React. Here's what I aim to achieve: I have separate mobile and desktop images in my application. Under the mobile image, there is a text ...

Angular version 4.X.X: Utilizing keyValueDiffer in your code

Looking for guidance on properly utilizing the keyValueDiffer in the latest Angular versions. I'm running into an issue where the create() method is deprecated due to changes in ChangeDetectorRef. this.diff = this.keyValueDiffer.find(obj).create(null ...

Angular displays incorrect HTTP error response status as 0 instead of the actual status code

In Angular, the HttpErrorResponse status is returning 0 instead of the actual status. However, the correct status is being displayed in the browser's network tab. ...

Encountering a challenge with triggering a dialog box from an onClick event on a pie chart in Angular 8 when utilizing chart.js

I am currently using a chart.js pie chart to showcase some data. I have managed to display the required information in an alert box when a slice of the pie is clicked. However, I am now looking for a way to present this data in a dialog box instead. &a ...

Steps for creating a copy of an Angular component

https://i.stack.imgur.com/4RMsR.png Whenever the user clicks on the Create Copy button, I aim to replicate the content of the DashboardComponent and position the duplicated version below the original one (the DashboardComponent featuring four dark blue sq ...

NextJS 13 causes tailwind to malfunction when route group is utilized

I've encountered an issue in my NextJS 13 application where Tailwind classes are no longer being applied after moving page.tsx/layout.tsx from the root directory to a (main) directory within the root. I suspect that there may be a configuration that i ...

Accessing form objects in Typescript with AngularJS

I am currently working with AngularJS and Typescript. I have encountered an issue while trying to access the form object. Here is the HTML snippet: <form name="myForm" novalidate> <label>First Name</label> <input type="text" ...

Troubleshooting the accessibility issue between Docker node container and Angular/Node.js

After deciding to follow the angular tutorial provided on the angular website, I made the choice to download the "node" image from dockerhub. To ensure proper functionality, I carefully mapped container ports 4200 and 8080 to my physical Windows machine po ...

Pushing out the both /browser and /server directories from an Angular SSR application to Azure Static Web Apps

Continuing from the discussion in this thread, my current challenge involves deploying my Angular SSR app to Azure SWA. I have successfully set it up for running and deployment (using the GitHub Action here): name: Azure Static Web Apps CI/CD on: push: ...

Nested component in reactive forms not functioning as expected

I've been experimenting with creating nested reactive form components. Specifically, I'm working on a reusable input component for my app within a reactive form. How can I dynamically communicate with nested components in Reactive forms? Despite ...

Pass a React component as a required prop in Typescript when certain props are necessary

I am currently working on a project where I need to create a custom TreeView component using React and Typescript. My goal is to have the ability to inject a template for each TreeNode in order to render them dynamically. My main challenge right now is fi ...

Typescript on Node.js Stream: the supplied arguments do not align with any of the available function signatures

While working in typescript, I encountered an issue while trying to implement a custom transform stream. The error message I received was supplied parameters do not match any signature of call target, specifically when calling the super constructor with th ...

A specialized React hook designed for fetching data in a continuous loop

Been struggling with this issue for hours :( I have a hook called useCollection which is designed to provide data retrieved from my API and updated in real-time using a websocket. It works perfectly for real-time updates, but I want it to also update the ...

Ways to acquire the reference of the parent component

Within my code, there is a parent component represented as: <Parent> <Child (click)=doSomething()></Child> </Parent> I am looking to establish a reference to the Parent component in order to pass it within a method that will trigg ...

Angular Universal's SSR causing a double page load event

Within my main code (app.component.html), there are no higher level NgIf statements that would trigger a reload. To prevent requests from being called after SSR sets the answers of public URLs, I am utilizing transferstate. I am also using isPlatFormBrows ...

The Subscription request did not trigger as expected

I encountered an issue where I needed to call two services in the OnInit step, but the second request was not being sent. As a workaround, I had to call them sequentially, which I believe is not the most efficient way to write the code. (Both services on t ...

Angular2 API call error: The function .map defaultOptions.merge is not recognized

When attempting to call the API using the post method, I encountered the following error message: this._defaultOptions.merge is not a function ... I looked into some solutions and tried importing the following without success: import 'rxjs/add/ope ...

"Disabling Click Event on Sidebar Menu in Angular: A Step-by-Step Guide

I am working on an Angular project with a sidebar that I want to modify in order to disable click events on the menu items. My goal is to guide users through a specific flow without allowing them to navigate freely. However, simply disabling the [routerLin ...

Error: The `ngMetadataName` property cannot be accessed because it is undefined or null in Internet Explorer version 10

Encountered an issue in IE 10 that is not present in IE 11: Error: TypeError: Unable to get property 'ngMetadataName' of undefined or null reference The property ngMetadataName can be found in the file vendor.js. This is the content of polyf ...

Utilizing nested endpoints in Angular resource with a Node.js server

In my Angular application, I have a resource called /cars with the endpoint defined as $resource('/cars/:carsId'); This allows me to retrieve all cars or a specific car. On the server side, I've implemented middleware to ensure that carsI ...