matan___4
matan___4

Reputation: 83

Angular: ngOnInit() called in every navigation

I work with Angular 9 and I use RouterModule.
I read somewhere that ngOnInit() function called only one time between navigations,
I mean every component initialized only once (ngOnInit() function).
I found that is not true.

Example of my code:
First, localhost/home loads HomeComponent and the following ngOnInit() called:

  ngOnInit(): void
  {
    console.log('init home component');
  }


Then, in HomeComponent I use [routerLink] to navigate to localhost/user which loads UserComponent,
and the following ngOnInit() called:

  ngOnInit(): void
  {
    console.log('init user component');
  }


Finally, in UserComponent I use [routerLink] to navigate to localhost/home which loads HomeComponent again,
and the following ngOnInit() called:

  ngOnInit(): void
  {
    console.log('init home component');
  }


As a result, HomeComponent DOES initialized again.
Am I missing something?
Thank you!

Upvotes: 2

Views: 2069

Answers (2)

Dave Skender
Dave Skender

Reputation: 621

Angular 9.x Components will reload with route navigation and will run the ngOnInit() when using the OnInit decorator. There may be some rare exceptions to this when using route parameters; however, re-initializing is the standard behavior. Modules and singleton services, on the other hand, are only initialized once.

For example, you can have [singleton] services load once (e.g. if you want variables to persist):

// user.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class UserService {
}

Ref: https://angular.io/guide/singleton-services

On a related note, while modules only load once, you can defer their loading to when the user accesses certain routes. This is helpful for larger apps that might take a long time to initially load. Lazy loading example:

// xxx-routing.module.ts
const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  }
];

Ref: https://angular.io/guide/lazy-loading-ngmodules

Upvotes: 2

Derek Kite
Derek Kite

Reputation: 1825

It depends how you navigate, and how your routes are configured. Say you have a route customer/addresses/edit and customer/addresses/view

The view and edit are child routes of addresses. You attach an id to them so you can fetch the address. Say you are in the view component, and you

router.navigate(['./edit', 33], {relativeTo: route});

it will not run ngOnInit of the address component. If you run

router.navigate(['customer/addresses/edit', 33]);

The whole component tree will be reloaded, and the ngOnInit methods will be called.

Upvotes: 1

Related Questions