Custom decorator for Angular component and ngOnInit

Viewed 1201

I'm trying to create a custom decorator to patch into the ngOnInit function on Angular components. My decorator gets called and I am able to grab the ngOnInit from the prototype but my replacement function never gets called during the component lifecycle. Does anyone know why my code doesn't work?

import {Component, OnInit} from '@angular/core';

function TestDecorator( theClass: Function ) {
   console.log( 'decorator called' );
   const ngOnInit = theClass.prototype.ngOnInit;
   theClass.prototype.ngOnInit = function() {
      console.log( 'decorator nginit' );
      ngOnInit();
   };
}

@TestDecorator
@Component( {
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
} )
export class AppComponent implements OnInit {
   title = 'angtest';

   constructor() {
      console.log( 'component constructed' );
   }

   ngOnInit(): void {
      console.log( 'component nginit' );
   }
}
1 Answers

I have been dealing with this issue for a while. In my case I was using Ivy, which I had to turn off in tsConfig.json. Just set enableIvy to false and restart your app and it should work.

You can also follow this issue on GitHub

Related