What could be causing ngOnInit to be called repeatedly in every instance?

According to the Angular documentation (https://angular.io/api/core/OnInit), ngOnInit is called immediately after the directive's data-bound properties are checked for the first time, but before any of its children are checked. It is a one-time invocation when the directive is created.

Although ngOnInit should be called only once, in the example provided by the plunker (taken from https://angular.io/tutorial/toh-pt5), I made modifications to both app/heroes/heroes.component.ts and app/dashboard/dashboard.component.ts to include console.log statements.

Upon opening the Developer Tools (F12), the console displayed repeated logs when the route was changed.

I researched various sources such as why ngOnInit is called twice?, the difference between Constructor and ngOnInit, Angular 2 App Component ngOnInit being called twice when using iframe, and ngOnInit being called every time the route is changed.

However, I could not comprehend why ngOnInit was triggering on each route change.


console.log("ngOnInit in All Heroes");
console.log("ngOnInit InDashBoard");

Answer №1

Whenever the route is altered, the component gets destroyed, and then when the route switches back, the component is reinitialized.

Try adding this code snippet to the DashboardComponent and witness it yourself:

    ngOnDestroy() {
      console.log("ngOnDestroy InDashBoard");
    }

Answer №2

I encountered an issue with how I was initializing the Child Components in my particular scenario. Within the metadata object of my @NgModule decorator, I mistakenly included the child component in the bootstrap property alongside the parent component. This incorrect setup caused my child components' properties to be reset and resulted in the OnInit() lifecycle method being triggered twice.

@NgModule({
 imports: [ BrowserModule, FormsModule ], // using 'FormsModule' for two-way data binding
 declarations: [ parentComponent, Child1, Child2], // all components
 //bootstrap: [parentComponent,Child1,Child2] // this caused issues with binding inputs in Child components
  bootstrap: [parentComponent] // only include parent components here
 })

Answer №3

It's possible that you're looking for OnInit to trigger twice. The key is being able to differentiate between the initial creation of the component and subsequent creations. If you want something to happen only on the first instantiation, then it should be included in the constructor. The constructor will only be called during the initial instantiation if the component is not Lazy loaded. On the other hand, if you need something to happen each time the route returns to the component, then it belongs in the OnInit method.

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

Angular - Error: Object returned from response does not match the expected type of 'request?: HttpRequest<any>'

While working on implementing an AuthGuard in Angular, I encountered the following Error: Type 'typeof AuthServiceService' is not assignable to type '(request?: HttpRequest) => string | Promise'. Type 'typeof AuthServiceServic ...

Issue with Angular ngFor: displaying only one name instead of all names in the loop

In my component.ts file, I have retrieved this data from an API call: [ [ { "name": "name one", "desc": "something here", }, { "name": &quo ...

Connection to mongo is currently unavailable for Middleware next

This code snippet shows a middleware for Next, which is designed to read the subdomain and check if it exists in the database. import { getValidSubdomain } from '@/lib/getValidSubdomain'; import { NextResponse } from 'next/server' impor ...

Determine if an object contains a specific key in Typescript and access the value associated with that

Here is a snippet of my code: let show = { createTag: false, updateFeature: false, createFeatureGroup: false, deleteFeature: false, deleteCycle: false, }; I am retrieving a value from the querystring that I want to compare against the ...

"Tips on updating the value of a BehaviorSubject with map, filter, find, or findIndex in an Angular

TS arrData = new BehaviorSubject<any>([]); ngOnInit() { const dataArr1 = [ { id: '1', name: 'Room1', spinning: true }, { id: '2', name: 'Room2&apos ...

In Angular, you can achieve two-way binding between a mat tab group and an array in your typescript file. But what's the best way to programmatically switch to a specific mat-tab using types

Check out the code snippet below. I have a mat tab group with a mat tab corresponding to each ValidationStep object in the validationSteps[] array in my TypeScript file through two-way binding. Whenever I add a new element to the array, a new tab is dynam ...

Connecting data from a .ts file in one webpage to the HTML content of another webpage

I am currently working on implementing the binding concept in Angular. The code snippet below is from PageOne.ts: this.navCtrl.push("PageTwo",{ paramType: params, }) Here is a snippet from PageTwo.html: <span>{{paramType}}</span> ...

I am encountering compilation errors while trying to run a basic react-dnd list using typescript

I'm currently working on implementing the beautiful-react-dnd example and encountering some errors: import * as React from 'react'; import { DragDropContext, Draggable, Droppable, DroppableProvided, DraggableLocation, DropResult, ...

Is there a way for me to access and install the Angular 2 release candidate through either npm or

When attempting to download Angular2 from npm or jspm, I am encountering an issue. Instead of getting the version 2.0.0-rc.1, I am receiving angular@^2.0.0-beta.17. Could this discrepancy be related to changes in the release candidate or it is a matter of ...

Is it recommended to ensure all of my components are nested within the root App component?

As I delve into learning Angular 4 with angular-cli for creating a web front end, I can't help but wonder about the structure of my components. In following the Heroes tutorial and applying it to my own data models, I noticed that all my components, ...

When using react-chartjs-2 with NextJS and typescript to create a bar chart, an error occurred: TypeError - Attempting to access properties of an undefined object (specifically 'map

Encountering a console error stating TypeError: Cannot read properties of undefined (reading 'map') . As I am new to NextJS & Typescript, I am attempting to build a simple bar chart. Error message: react-dom.development.js?03cb:22839 Uncaugh ...

Protractor typescript guide: Clicking an element with _ngcontent and a span containing buttontext

I'm struggling with creating a protractor TypeScript code to click a button with _ngcontent and span buttontext. Does anyone have any ideas on how to achieve this? The code snippet on the site is: <span _ngcontent-c6 class="braeting net-subheadi ...

Looking for a way to display specific JSON data on the home.html page with just a click?

In the home.ts file, I have a JSON object stored as json_html. It looks like this: public json_html = { "button1":"<p><b>first section<b></p>", "button2":"<p>second section</p>", "button3":"<p><b&g ...

The dreaded error message [ERR_REQUIRE_ESM] has appeared, indicating that the require() function for an ES

I am currently developing a Discord bot using TypeScript and discord.js. However, when I attempted to compile the code this morning, I encountered the following error: C:\SECRET\Kostegator\dist\Util\getMeme.js:17 const node_fetch_1 ...

What is the connection between tsconfig.json and typings.json files?

I recently acquired a .NET MVC sample application that came with Angular2-final. Within the project, I noticed a typings.json file at the root and a tsconfig.json file in the ng2 app directory. What is the connection between these two files? Is this the mo ...

Error message "After the upgrade to Angular 15, the property 'selectedIndex' is not recognized in the type 'AppComponent'."

My Ionic 6 app with capacitor has been updated in the package.json file. These are the changes: "dependencies": { "@angular/common": "^15.1.0", "@angular/core": "^15.1.0", "@angular/forms": "^15.1.0", "@angular/platform-browser": "^15.1. ...

How come ngOnChange is unable to detect changes in @Input elements when ngOnDetect is able to do so?

Check out this plunker Please note: In order to see the effect, you need to restart the app after entering the link. import {Component, OnInit, Input, OnChanges, DoCheck} from 'angular2/core' @Component({ selector: 'sub', templat ...

Using TypeScript and the `this` keyword in SharePoint Framework with Vue

I'm currently developing a SharePoint Framework web part with Vue.js. Check out this code snippet: export default class MyWorkspaceTestWebPart extends BaseClientSideWebPart<IMyWorkspaceTestWebPartProps> { public uol_app; public render(): ...

TS Intellisense in Visual Studio Code for JavaScript Events and File Types

Whilst attempting a similar action, onDragOver(event: Event): void in Visual Studio Code, an error is thrown by IntelliSense: [ts] Cannot find name 'Event'. The same issue arises when trying something like this: let file: File = new File() ...

Creating objects in Angular 2 through HTTP GET calls

Recently, I've delved into learning Angular 2. My current challenge involves making http get requests to retrieve data and then constructing objects from that data for later display using templates. If you believe my approach is incorrect, please feel ...