Angular Lifecycle Hooks
Lifecycle hooks let a component react at defined points in its Angular lifetime. Choose the hook based on the work’s requirements rather than assuming construction means the view is ready.
How it works
The constructor is suitable for dependency setup, while ngOnInit runs after initial inputs have been initialized. Work that needs actual rendered elements belongs at an appropriate render callback, not in a constructor that runs before those elements exist. The example uses a simple initialization message so the order is easy to observe without relying on layout timing or a browser-specific measurement.
Run the code
Use a separate empty project folder with a compatible Node version: ^22.22.3, ^24.15.0 or a supported 26+ runtime. The review uses Node 24.22.1, Angular 22.2.4, CLI/build 22.2.5 and TypeScript 6.0.3. Node 22.15.1 is too old for Angular 22. Save every download at its displayed path; browsers may keep only the basename, so recreate the src folder. Run npm install, npm run build and npm start, then open the loopback address printed by the server. Run npm test for the supplied component tests. These are local teaching projects, not Bhylu publishing files.
The small loopback server serves the compiled app and fixed, read-only tool API fixtures. It is not a database, authentication or lending service. Angular examples do not run in Bhylu’s current HTML or TypeScript playground. No Apache, MySQL or PHP configuration change is needed.
Example
import { Component } from '@angular/core';
import { OnInit, signal } from '@angular/core';
@Component({
selector: 'bh-lifecycle',
standalone: true,
imports: [],
template: `<p data-result>{{ message() }}</p>`,
})
export class App implements OnInit {
message = signal('Constructed');
ngOnInit(): void {
this.message.set('Initialized with Angular');
}
}
Expected result
Initialized with Angular
The stable first view contains the initialization message. Later input changes should be handled through reactive dependencies or the relevant change lifecycle, not by repeatedly assuming ngOnInit will run. Clean up resources at destruction even when a component is removed through a router or conditional block.