TL;DR
We are building an app with Angular 2 and would like to register a \"global\" ngOnInit and ngOnDestroy function. Wit
Forcing the behaviour for the entire app wouldn't be a good idea, this affects third-party components as well for starters.
Boilerplate code can be moved into concrete base class. There are solutions for JS/TS multiple inheritance, e.g. @mixin, see also TypeScript guide.
Since base class methods are fixed, class mixin can be expressed as a simplified decorator:
class CustomLifecycle implements OnInit, OnDestroy {
constructor(
public originalNgOnInit: Function,
public originalNgOnDestroy: Function
) {}
ngOnInit() {
...
if (typeof this.originalNgOnInit === 'function') {
this.originalNgOnInit();
}
}
ngOnDestroy() {
...
if (typeof this.originalNgOnDestroy === 'function') {
this.originalNgOnDestroy ();
}
}
}
function Lifecycled() {
return function (target: Function) {
const customLifecycle = new CustomLifecycle(
target.prototype.ngOnInit,
target.prototype.ngOnDestroy
);
target.prototype.ngOnInit = customLifecycle.ngOnInit;
target.prototype.ngOnDestroy = customLifecycle.ngOnDestroy;
}
}
And it can be used like
@Component({ ... })
@Lifecycled()
class SomeComponent { .... }
The implementation is limited to ngOnInit, etc. prototype methods, arrow members require a constructor to be patched.