Angular component and ngOnInit custom decorator

I have been working on creating a custom decorator to integrate into the ngOnInit function in Angular components. While I am successfully able to access the ngOnInit from the prototype within my decorator, my replacement function is not being called during the component lifecycle. I'm puzzled as to why my code doesn't seem to be functioning properly. Can anyone provide insight into what might be causing this issue?

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

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

@CustomDecorator
@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' );
   }
}

Answer №1

After struggling with this problem for some time, I finally found a solution that worked for me. In my situation, I was utilizing Ivy and had to disable it in my tsConfig.json file. Simply set the enableIvy parameter to false, restart your application, and see if that resolves the issue.

If you're still having trouble, you can refer to this discussion on GitHub for additional guidance.

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

Creating a personalized React date selection tool using TypeScript

After following the instructions in the documentation for creating a custom datepicker, I finally managed to build one. However, I encountered an error stating "Function components cannot be given refs. Attempts to access this ref will fail. Did you mean ...

What is the rationale behind Angular 2 and Angular 4's use of banana brackets? Is there a particular reason for this departure from AngularJS's pattern?

Although not directly related to coding, the syntax in AngularJS can still be followed: <input ng-model="hero.name" placeholder="name" type="text"> Here is an example of the syntax used in Angular 2 and its newer versio ...

Utilize prop-types inheritance when a component is rendered via props

Is it possible to inherit prop-types when a component is rendered via the parents prop, without direct access to 'ChildProps' and 'Props' interface? Parent Component interface ChildProps { counter: number; setCounter: React.Dispat ...

Why does TypeScript not recognize deconstructed arrays as potentially undefined variables?

When looking at the code snippet below, I was under the impression that the destructured array variables, firstName and lastName, would be classified as string | undefined. This is because the array being destructured could have fewer variables compared ...

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 ...

Creating Excel documents using Angular and XLSX template generator

In my Angular application, I am utilizing the XLSX library to manipulate an Excel file. The file I start with is encoded in base64 format, so my first task is to decode it, make some changes to specific cells, and then save the modified file back in base64 ...

What is the reason for the absence of a PasteEvent type in the types/jquery library?

Why doesn't jQuery have a specific type for PasteEvent or ClipboardEvent? While there is a standard type for paste events (ClipboardEvent), jQuery does not have a specific event type for it. view image description here view image description here I ...

Utilizing TypeScript generics to accurately extract type information from state during reduction

In the context of a state reducer presented as follows: const anObject = { fruit: 'Apple', today: new Date(), } function reducer(state, stateReducer) { return stateReducer(state); } const fruit = reducer(anObject, state => state.fruit ...

Guide to Integrating BLK Theme into an Angular CLI Project

I've recently set up an Angular project using CLI and I am interested in integrating the BLK theme by Creative Tim into this project. However, the only available option from Creative Tim is to download a pre-existing project and build upon that framew ...

Initiate API request using the POST method in Angular version 4.4.7

Having trouble calling my services, I need to make API calls using the Basic + Hash method for Token authentication. Afterwards, I must send this token response to all services. I have several services that consume from localhost:8080 with POST and GET me ...

Reactivate stripe subscription based on the payment date instead of the original renewal date

In my Typescript application, I have integrated Stripe subscriptions. Let's consider a scenario where a customer is on the monthly plan for $10 with auto-renewal set up. Now, if this customer has an expired card on file and misses payment on the auto- ...

Collaborate and apply coding principles across both Android and web platforms

Currently, I am developing a web version for my Android app. Within the app, there are numerous utility files such as a class that formats strings in a specific manner. I am wondering if there is a way to write this functionality once and use it on both ...

The method window.getComputedStyle retrieves the CSS max-height property containing an unresolved calc() function

Has anyone encountered a challenge with a function related to Angular in their project? Here is a snippet of the code causing issues: console.log(window.getComputedStyle(this.frontLayer.nativeElement).maxHeight); And within the component template: <di ...

Unable to display Cell Properties in Angular using CKEditor 5 table toolbar configuration

While utilizing the CKEditor 5 official demo, I noticed that the table content Toolbar includes Cell properties. This feature is crucial for my needs, but despite configuring my table similarly to the demo setup, the Cell properties do not appear. The dem ...

express-typescript-react: The frontend bundle file could not be located (404 error)

Currently, I am in the process of developing a full stack application that utilizes Express (written in Typescript) and React. One key component of my development setup is webpack, which I'm using to bundle both the backend and frontend parts of the a ...

A function that takes an array of objects and combines all their keys to create a single unified object representing all the information

I have a JavaScript function that accepts an array containing zero or more objects of type {string => async fn*(...) => ...} (with the asterisk indicating async generator functions). This function will output a single object which combines all keys ...

Determine whether a response is not received within 8 seconds

One of the methods in my Angular component is responsible for returning data Here is a snippet of that method getRecognitionById() { this.loaderService.show(null, true); forkJoin( this.vendorWebApiService.getRecognitionById(this.executiveCh ...

How to filter an array in Angular 4 without the need for creating a new array and then displaying the filtered results within the same

In my collection of students, I have their names paired with their academic outcomes. studentResults = [ {name: 'Adam', result : 'Passed'}, {name: 'Alan', result : 'Failed'}, {name : 'Sandy', result : &ap ...

Declaring TypeScript globally within a function scope

A Node.js script includes a function that needs to be evaluated in the browser context rather than the Node.js environment. This can lead to TypeScript type errors as the function body references variables that are only defined in the browser: // Node con ...

Guide on simulating rxjs/Websocket in angular for performing Unit Testing

I have developed a service that manages websocket communication with a server and I am looking to create unit tests for it. However, I am facing challenges in mocking rxjs/Websocket. While searching for a solution, I came across a similar question here, b ...