Skip to content Skip to sidebar Skip to footer

Extend Angular Component Method With Injected Services

I have to handle Angular component's destruction event in my external module providing decorating function. Unfortunately I am unable to override ngOnDestroy() method when it conta

Solution 1:

ngOnDestroy method is overridden with listed decorator. The actual problem with it is that wrong context is applied to originalFunction in

originalFunction.apply(target, arguments);

In case of method/property decorators target argument is 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 ngOnDestroy method doesn't necessarily exist but the decorator should be applied any way, it can be class decorator instead, where target is 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 ...

Post a Comment for "Extend Angular Component Method With Injected Services"