The Angular variable binding issue persists upon reloading the page or browser, yet functions seamlessly when navigating between routes

My subscribe button displays the text "Subscribe" when the page loads, but upon reloading the page, the text disappears. The button text is controlled by TypeScript code, and strangely, when I navigate to another route, the text magically reappears.

HTML

<button type="button" (click)="subscribe()" name="subscribe" id="subscribe">
    <span *ngIf="!subscribeFormProcessing">Subscribe</span>
    <span *ngIf="subscribeFormProcessing"><img [src]="btnLoaderUrl"></span>
</button>

Typescript

export class FooterWidgetComponent implements OnInit, OnDestroy {

    subscribeEmailAddress: string;
    subscribeEmailSubscriber: any;
    btnLoaderUrl: string;
    subscribeFormProcessing = false;
    subscribeMsg: string;

    constructor(private appSettingsService: AppSettingsService, private httpRequestService: HttpRequestService) {
    }

    ngOnInit() {
        this.subscribeEmailAddress = '';
        this.subscribeMsg = '';
        this.btnLoaderUrl = this.appSettingsService.getImagesBaseUrl() + 'app/btn-loader.gif';
        this.subscribeEmailSubscriber = this.httpRequestService.requestCompleted.subscribe(data => {
            this.subscribeFormProcessing = false;
            if (data['status'] === "success") {
                this.subscribeMsg = data['message'];
            } else {
                this.subscribeMsg = data['message'];
            }
            this.clearSubscribeMessage()
        });
    }

    clearSubscribeMessage() {
        setTimeout(() => {
            this.subscribeMsg = '';
        }, 5000);
    }

    subscribe() {
        this.subscribeFormProcessing = true;
        this.httpRequestService.setUrl('subscribe');
        this.httpRequestService.sendPost({email: this.subscribeEmailAddress});
    }

    ngOnDestroy() {
        this.subscribeEmailSubscriber.unsubscribe();
    }

}

On Page Reload

https://i.sstatic.net/E7KNM.png

After navigating to any route

https://i.sstatic.net/Ly0OP.png

Root Cause I am using Addthis widget for sharing post and blog. Initializing the addthis on blog page load seems to be causing this particular issue.

initAddThisToolbar() {
        addthis.layers.refresh();
    } 

HTML

<div class="addthis_inline_share_toolbox"></div>

Is there a different method to refresh the addthis widget?

Answer №1

When the page refreshes, the onDestroy() method is not called. This results in your description never being dropped and

this.httpRequestService.requestCompleted.subscribe()
not getting called a second time. The onInit() function still executes, causing this.subscribeFormProcessing to remain true.

To address this issue, you need to unsubscribe from this.subscribeEmailSubscriber during the reload process. Here is a possible solution:

ngOnInit(): void {
   // Check if there is an active subscription
   // If so, unsubscribe
   if (this.subscribeEmailSubscriber) {
       this.subscribeEmailSubscriber.unsubscribe();
   }

   // Rest of the code remains unchanged
   this.subscribeEmailAddress = '';
   this.subscribeMsg = '';
   this.btnLoaderUrl = this.appSettingsService.getImagesBaseUrl() + 'app/btn-loader.gif';
   this.subscribeEmailSubscriber = this.httpRequestService.requestCompleted.subscribe(data => {
        this.subscribeFormProcessing = false;
        if (data['status'] === "success") {
            this.subscribeMsg = data['message'];
        } else {
            this.subscribeMsg = data['message'];
        }
        this.clearSubscribeMessage()
   });
} 

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

Automatically refresh your Angular 4 frontend with Spring Boot for seamless integration

Currently, I am in the process of developing a web application using Angular4 and Spring Boot java with gradle. I have successfully configured my gradle tasks following the instructions provided in this resource. By executing ./gradlew bootRun, both Java a ...

Having trouble locating node_modules post deployment?

Although the title may lead you astray, please stay with me for a moment. I've created a basic Angular2 application in Visual Studio 2015 and have now deployed it to Azure. While having node_modules in the development environment worked perfectly fi ...

Tips for sending information back to the previous screen in React Native Navigation version 5

Recently, I upgraded to react native navigation version 5 and now I am facing an issue with sending data back to the previous screen when making a goBack() call. To navigate to the next view, I use: const onSelectCountry = item => { console.log(it ...

Unable to find solutions for all parameters in AngularFirestoreDocument: (?, ?)

I have integrated Angular 11 with Firebase for authentication and Firestore for data collection. However, I encountered an error message Can't resolve all parameters for AngularFirestoreDocument: (?, ?). How can I resolve this null injector issue? On ...

Is there a way to send routerLink to an HTML element like <div [innerHTML]=""> without triggering the warning: "sanitizing HTML stripped some content"? Check out https://g.co/ng/security#xss for more information

Within the parent component, I am using the following construction: const link = `<a routerLink="${group.id}">${group.name}</a>`; // also tried using [routerLink] When attempting to work with it in a child component, I implement it l ...

Custom objects do not return true for Symbol.hasInstance

The TypeScript playground encounters an issue with the Symbol.hasInstance built-in symbol, while it functions properly for other symbols. Testing other symbol methods such as Symbol.match and Symbol.replace show no problems, but Symbol.hasInstance is not ...

Which one should you begin with: AngularJS or Angular 2?

Interested in learning Angular and curious about the differences between Angular, AngularJS, and Angular 2. Should I focus on educating myself on Angular or go straight to Angular 2, considering it's now in beta version? Is there a significant differ ...

Is there a feature in Stepper that allows for event handling when steps are changed?

For my project, I am utilizing the mat-stepper component along with a mat-Datatable inside it. In each step of the stepper, I need to dynamically hide and show different columns based on some data. Is there a way to send this data to trigger changes at eve ...

Issue: The last loader (./node_modules/awesome-typescript-loader/dist/entry.js) failed to provide a Buffer or String

This issue arises during the dockerhub build process in the dockerfile. Error: The final loader (./node_modules/awesome-typescript-loader/dist/entry.js) did not return a Buffer or String. I have explored various solutions online, but none of them have pr ...

Issue with action creator documentation not displaying comments

We are exploring the possibility of integrating redux-toolkit into our application, but I am facing an issue with displaying the documentation comments for our action creators. Here is our old code snippet: const ADD_NAME = 'ADD_NAME'; /** * Se ...

Exploring TypeScript Compiler Options for ensuring code compliance beyond the confines of strict mode

Our goal is to set up TypeScript Compiler (TSC) with a command line option that can identify errors when developers declare class fields using implicit type expressions instead of explicit ones as illustrated below. class Appliance { //Desired coding ...

Assembly of these elements

When dealing with a structure where each property is of type These<E, A> where E and A are unique for each property. declare const someStruct: { a1: TH.These<E1, A1>; a2: TH.These<E2, A2>; a3: TH.These<E3, A3>; } I inte ...

Incorporating Past Projects into an Angular 2 Website

Some time ago, I built a Javascript game utilizing the HTML canvas element for image rendering. Now that I have a personal website created with Angular 2, I am unsure of how to properly embed my game into my site. Due to Angular 2 removing the script tag ...

Integrating Auth0-js with the usePostMessage functionality

Encountering difficulties when compiling an Angular application that incorporates the auth0-js package. The code utilizes the method renewAuth(options: RenewAuthOptions, callback: Auth0Callback<any>): void;, yet it seems to be causing issues as the p ...

Error encountered while attempting to obtain OAuth2 API authorization token in ExpressJS Node.js Angular: "getaddrinfo ENOTFOUND"

Recently, I developed an angular application that sends an HTTP post request to a Node/Express.js endpoint upon clicking a button in order to obtain an authorisation token. I successfully configured the necessary credentials for basic OAuth2 authorisation ...

Retrieving component attributes using jQuery or alternate event handlers

In my Angular2 component, I am facing an issue with using vis.js (or jQuery) click events. Despite successfully displaying my graph and catching click events, I encounter a problem where I lose access to my component's properties within the context of ...

The object prototype can only be an instance of an Object or null; any other value will

While attempting to create a codesandbox in order to replicate a bug, I encountered an additional issue. You can view my codesandbox here: https://codesandbox.io/s/vue-typescript-example-o7xsv The error message states: Object prototype may only be an ...

React encountered an issue: each child element within a list must be assigned a unique "key" prop

I am feeling a bit puzzled as to why I keep getting the error message: child in a list should have a unique "key" prop. In my SearchFilterCategory component, I have made sure to add a key for each list item using a unique id. Can you help me figu ...

The Angular component seems to be lacking a template

During the upgrade process of my Angular 8 app to Angular 9, I encountered an error message while trying to build: ERROR in component is missing a template The issue is that it doesn't specify which specific component is missing a template. Is there ...

What is the method for defining a CSS property for the ::before pseudo element within an Angular component?

Can TypeScript variables be accessed in SCSS code within an Angular component? I am looking to achieve the following: <style type="text/css"> .source-status-{{ event.status.id }}::before { border-left: 20px solid {{ event.status.colo ...