Performance: ngOnInit for initialization
This affects the initial rendering speed and responsiveness by controlling when component initialization logic runs.
import { OnInit } from '@angular/core'; export class MyComponent implements OnInit { ngOnInit() { this.loadData(); } loadData() { // heavy synchronous logic } }
export class MyComponent { constructor() { this.loadData(); } loadData() { // heavy synchronous logic } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Initialization in constructor | Immediate heavy DOM changes | Multiple reflows if DOM updated synchronously | High paint cost delaying first paint | [X] Bad |
| Initialization in ngOnInit | DOM changes after inputs set | Single reflow after initialization | Lower paint cost, faster first paint | [OK] Good |
ngOnInit method in an Angular component?ngOnInit lifecycle hook runs after Angular creates the component, making it ideal for initialization tasks.ngOnInit.ngOnInit in an Angular component?ngOnInit are methods declared as ngOnInit() { ... }.export class MyComponent implements OnInit {
data = '';
ngOnInit() {
this.data = 'Hello World';
}
}data after the component initializes?data starts as an empty string.ngOnInit, data is set to 'Hello World'. This runs after component creation.export class SampleComponent implements OnInit {
message: string;
ngOnInit() {
this.message = 'Welcome';
}
}OnInit but does not import it from '@angular/core'. This causes a compile error.ngOnInit is correct, and initializing message in ngOnInit is valid.ngOnInit runs after component creation and is the recommended place to start fetching data once.ngOnDestroy runs when component is destroyed, and button click handlers run on user action, not automatically.Pass the test and this pattern moves unknown