Unleash the full power of Angular Components by enhancing them with injected

I am facing a challenge with handling the destruction event of an Angular component in my external module that provides a decorating function. I've run into issues trying to override the ngOnDestroy() method when it includes references to injected services. Is there a workaround or another way to achieve the same result?

Check out this Plnkr for more information: https://plnkr.co/edit/YtczREB91A3t6rJ1uKks (error related to ngOnDestroy() should not occur)

If anyone is interested, here is a working version thanks to @estus's suggestion involving the use of Symbol(): https://plnkr.co/edit/nnxLswhPUGZR3ycBWojg

Answer №1

When using the ngOnDestroy

method and applying a decorator, it's important to note that the wrong context can sometimes be applied to the
originalFunction
in the process.</p>

<pre><code>originalFunction.apply(target, arguments);

In situations involving method/property decorators, the target argument typically refers to the class prototype for instance properties/methods:

export const ON_DESTROY_SYMBOL = Symbol();

export function Decorator() {
  return (target: any, propertyName: string) => {
    target[ON_DESTROY_SYMBOL] = target.ngOnDestroy;
    target.ngOnDestroy = function() {
      this[ON_DESTROY_SYMBOL]();
      console.log('Component destroy event successfully handled!');
    }
  }
}

If the ngOnDestroy method may not always exist but the decorator still needs to be applied, it can instead be implemented as a class decorator where the target refers to the class constructor:

export function Decorator() {
  return (target: any, propertyName: string) => {
    target.prototype[ON_DESTROY_SYMBOL] = target.prototype.ngOnDestroy || () => {};
    target.prototype.ngOnDestroy = function() {
      this[ON_DESTROY_SYMBOL]();
      console.log('Component destroy event successfully handled!');
    }
  }
}

...
Decorator()
Component(...)
class ...

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

Animation that increments to a predetermined value

I'm trying to create a counter animation that dynamically animates a value calculated by the checkboxes selected. The calculation is working fine, but the animation is not happening. http://jsfiddle.net/dbtj93kL/ $('input[type="checkbox"]&apo ...

When Ajax responseText and echo fail, the header file contents are sent back instead

I have a section of code in my PHP file called thePhpFile.php that is used to handle an Ajax call: <?php require_once('usefulStuff.php'); // includes useful functions if (isset($_GET['zer'])) { $bFound = false; if(! $bF ...

reveal the concealed divs within the list elements

html: In my HTML document, I have a unordered list (ul) with each list item (li) constructed like this: <li class="A">list-item <div>1</div> <div class="B">2 <div class="C">3</div> </div> ...

Sleek descending motion effect

I have created a simple function, but it is not animating smoothly and seems to lag... I am using it for a div sized at 1600x700 pixels on page load $(document).ready(function(){ $('#slider').slideDown(500); }); Is there any way to ensure s ...

Using Sinonjs fakeserver to handle numerous ajax requests

I utilize QUnit in combination with sinon. Is there a way to make sinon's fakeserver respond to multiple chained ajax calls triggered from the same method? module('demo', { beforeEach: function(){ this.server = sinon.fakeServer. ...

Incorporate Stripe Elements into your Nuxt Js application

I recently managed to integrate Stripe into my React + Spring Boot application by following the guidelines provided in this documentation: https://stripe.com/docs/stripe-js/react. I used it in my React class component. Now, I am transitioning to Nuxt from ...

How can I retrieve the `checked` state of an input in Vue 3 using Typescript?

In my current project, I am using the latest version of Vue (Vue 3) and TypeScript 4.4. I am facing an issue where I need to retrieve the value of a checkbox without resorting to (event.target as any).checked. Are there any alternative methods in Vue tha ...

The Material-ui Select component is experiencing issues with updating the state accurately

When creating a multiple select input using Material-UI, I encountered an issue with setting the default selected values from state. Despite having an array of two objects in the state and setting it as the select value, the default objects are not being ...

What is the best way to retrieve the value of an nth column in a table using

Is there a way to retrieve the value of a specific column in a table? For example, I want to get the value of the 2nd column. I have no trouble getting the first one using this method - it works perfectly fine. However, when I try to retrieve the value of ...

JavaScript: Struggles with utilizing a function as an argument and later executing it inside a nested function

I've been struggling with defining a new function, and I need help resolving it. Here's an example that I was initially referencing: Pass arguments into ajax onreadystatechange callback? I wasn't able to find the solution through research, ...

The most secure method for retrieving User Id in AngularFire2

I'm currently facing a dilemma in determining the most secure method to obtain an authenticated user's uid using AngularFire2. There seem to be two viable approaches available, but I am uncertain about which one offers the best security measures ...

Tips for updating components with fresh data in Next.JS without having to refresh the page

As part of my Todo-App development project, I am utilizing technologies such as Next.JS, Prisma, Typescript, and PostgreSQL. The data retrieval process involves the API folder interacting with the database through Prisma. CRUD operations on the Task table ...

What is the process for personalizing the appearance in cdk drag and drop mode?

I have created a small list of characters that are draggable using Cdk Drag Drop. Everything is working well so far! Now, I want to customize the style of the draggable items. I came across .cdk-drag-preview class for styling, which also includes box-shado ...

What is the best method to generate a distinct identifier for individual input fields using either JavaScript or jQuery?

I have attempted to copy the table n number of times using a for loop. Unfortunately, the for loop seems to only work on the first iteration. I am aware that this is due to not having unique IDs assigned to each table. As a beginner, I am unsure how to cre ...

The XMLHttpRequest response states that the preflight request did not meet the access control check requirements

I am attempting to subscribe to a firebase cloud messaging topic by sending an http post request. var data = null; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState ...

Once appearing, the element quickly vanishes after the fadeIn() function is

In the source code, there is a section that looks like this: <div class="dash page" id="home"> <?php include ('pages/home.php'); ?> </div> <div class="dash page" id="screenshots"> <?php include ('pages/scr ...

Syncing a line's position with the cursor in Angular using the ChartJs Annotation Plugin

I've been working on creating a crosshair using the annotation plugin, and while I've been able to modify the line's value, it doesn't seem to update on the chart. Here are the details of my chart options : public financialChartOptions ...

Filtering an Array of Objects on the Fly in Vue.js

I'm currently working on a Vue.js app where I need to dynamically apply filter values to an Array of objects based on their field values. Each object in the Array has various fields that I want to filter by. The challenge is that each field can have m ...

Issue with migrating from Angular version 2.4.10 to 4.0.0

After attempting to update my application from Angular 2.4.10 to 4.0.0, I used the following command: "npm install @angular/common@next @angular/compiler@next @angular/compiler-cli@next @angular/core@next @angular/forms@next @angular/http@next @angular/pl ...

Updating data within rows in Angular 4

Is there a way for me to update the value in my row based on a selected ingredient from a dropdown list? I want the unit price to be patched into the input field when a specific ingredient is chosen. You can find the relevant code snippets by visiting TH ...