Angular's ngOnDestroy lifecycle hook does not execute as expected after a button click event

When working on my HTML code, I encountered the following:

<div class="form-group">
                  <button type="submit"

                          value="submit"
                          class="btn btn-secondary btn-float">Upload</button>
                </div>
              </div>

In my TS file, I have the following code snippet:

export class testComponent implements  OnDestroy {

ngOnDestroy() {
    console.log("Fired ngOnDestroy");
  }

onClickSubmit() {

      this.subscription = this.service
        .create(test, url)
        .subscribe(
              res => {

                console.log('HTTP response', res)
              },
              err => {

                console.log("Error", err)
              },
              () => console.log('HTTP request completed.')
        );

  }
  }

I am facing an issue where after clicking the button to call the service, my ngOnDestroy() method is not being fired. I am unsure why this is happening and could use some assistance.

Answer №1

ngOnDestroy is a method that the framework invokes when a component is removed from the DOM.

Your example does not indicate that the button click necessarily leads to destruction.

In the scenario where I have a certain component, ngOnDestroy will be triggered within the child component upon clicking the button.

<child *ngIf="!deleted"></child>
<button (click)="deleted = true">Trigger destroy in child</button>

DEMO: https://stackblitz.com/edit/angular-fxvj1n

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

Update the status of the reactive form control to invalid

I'm attempting to mark a form control as invalid, however, the following code snippet is not producing the desired result this.currencyForm.controls['currencyMaxSell'].setErrors({smallerThan: true}) ...

CodeIgniter encountering a dilemma with session logout functionality

if ($this->Adminmodel->check_credentials($this->input->post('email'), $this->input->post('password')) =="true") { redirect("admin/dashboard"); } ...

Executing blur event in AngularJS

Is there a way to set up an input so that when the length is equal to 5, it triggers a blur event automatically? Any tips on how to achieve this? Here is a basic concept of what I'm looking for: <input type="tel" placeholder="type here." ...

Using @PathVariable in Spring MVC can cause issues with Ajax functionality

I am facing an issue where I need to incorporate an ajax function on a specific page, but it seems to be not working with @PathVariable in spring mvc. page1.jsp <li><a href="page2/sss">WatchEvent</a></li> 1) It is working pr ...

Navigation that remains fixed while scrolling

Can someone help me fix the side navigation of this template to stay fixed when a user scrolls past it for easier navigation? I'm struggling with the code and could use some fresh eyes to look at it. I just can't seem to figure it out on my own, ...

Alter the border line's color based on the specific section or div it overlays

I am attempting to utilize jQuery in order to change the color of my border line depending on its position within the divs. I have set the position to absolute and it is positioned on both divs. My goal is to make the line on the top div appear as grey, wh ...

Can a file object be transmitted using this method?

I'm new to jquery and I am attempting to upload a File object obtained from my HTML: <label for="photo" class="col-xs-2">Photo</label> <input id="photo" name="fileName" type="file" class="col-xs-4"/> This is the snippet of my J ...

Creating a generic groupBy function using Typescript

Questioning the TypeScript compiler's comprehension of my groupBy function, which includes an optional transformer for post-grouping data modification. Seeking suggestions on what steps to take next. const customGrouping = <A extends {}, C, B exten ...

Having some trouble while attempting to set up the next-auth@beta package due to an error

Currently encountering the following error message: code EUNSUPPORTEDPROTOCOL Unsupported URL Type "workspace:": workspace:* I have made sure to update my node to the most recent recommended version. In a previous project, I successfully instal ...

Include a button alongside the headers of the material table columns

I am looking to customize the material table headers by adding a button next to each column header, while still keeping the default features like sorting and drag-and-drop for column rearrangement. Currently, overriding the headers requires replacing the e ...

What is the best way to modify the colors of two specific elements using a combination of CSS and JavaScript

I am currently developing a browser-based game and have encountered an issue. Here is the relevant line of my HTML/PHP code: echo '<div id="div'.$n.'" class="d'.$rand.'" onclick="swapit(this.id, this.className)"></di ...

Issue with ImageButton Not Triggering UpdatePanel in Asp.net

I am encountering an issue with a button click event inside an asp.net update panel. Here is my code: My Aspx Code : <asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional"> <ContentTemplat ...

Obtain the result returned from a JSON using jQuery's Ajax GET

Can you help me figure out how to retrieve the JSON result of a PHP function in an Ajax request for verification purposes in onSucces? public function checkEmailValidityAction() { $is_valid = true; $is_duplicate = false; $email_reset = false ...

Transform the array of strings

I'm currently working with an array that looks like this: ["[Date.UTC(2016,09,30),250500.00]","[Date.UTC(2016,09,29),255100.83]", "[Date.UTC(2016,09,28),255600.82]"] What would be the best way to transform it into a structure like this? [[Date.UTC( ...

Ways to selectively deactivate client-side functionality

I have implemented a server-side rendered app with transitions, including a 404 error page that I placed in a lazy module to avoid increasing the size of loaded JavaScript. While this setup is functioning correctly, there is some flickering when the clien ...

Adding information to a database by utilizing Jquery, Ajax, and PHP

Trying to use ajax to submit data to a database has been a challenge for me. Even with a simple code test, I can't seem to make it work. Here is the HTML/ajax code snippet: <?php include("osb.php");?> <script type = "text ...

problem encountered when running "ionic cordova build android --prod --release"

A chat application has been developed using Ionic2. Upon attempting to generate a production build with ionic cordova build android --prod --release, the following error is encountered. Error: ./node_modules/rxjs/observable/BoundCallbackObservable.js ...

You cannot modify a variable inside an event handler function unless it is declared globally in the code

I am facing an issue with my nodejs backend app that uses mongoose for database connections and queries within an event handler of socket.io. Specifically, the problem arises when I try to update a variable within a callback function of a mongoose query in ...

What is the best way to convert this into a distinct function using typescript?

Is there a way to create a single method in Protractor or Webdriver API that can get the browser width and height? const getWindowWidth = async () => { const size = await browser.manage().window().getSize(); return size.width; }; I need this metho ...

Avoiding server requests in Firefox by refraining from using ajax

I've implemented the following jquery code: $("#tasksViewType").selectBox().change( function (){ var userId = $('#hiddenUserId').val(); var viewTypeId = $("#tasksViewType").val(); $.post('updateViewType& ...