Performance: Why lifecycle hooks matter
Lifecycle hooks affect how and when Angular components update, impacting rendering speed and responsiveness.
ngOnChanges(changes) {
if (changes['inputData']) {
this.calculateSomethingExpensive();
}
}ngDoCheck() {
// heavy computation or DOM manipulation here
this.calculateSomethingExpensive();
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy logic in ngDoCheck | Many unnecessary DOM reads/writes | Multiple reflows per cycle | High paint cost due to layout thrashing | [X] Bad |
| Conditional logic in ngOnChanges | Minimal DOM operations only on input change | Single reflow when needed | Low paint cost | [OK] Good |
ngOnInit lifecycle hook in an Angular component?ngOnInit with exact casing.ngOnInit() { ... } inside the component class.export class MyComponent implements OnInit {
constructor() { console.log('Constructor called'); }
ngOnInit() { console.log('ngOnInit called'); }
}ngOnInit runs after Angular sets input properties.export class SampleComponent implements OnInit {
ngOnInit() {
this.loadData();
}
loadData() {
console.log('Data loaded');
}
ngOnDestroy() {
this.loadData();
}
}ngOnInit to run code once after component creation, perfect for fetching data.ngOnDestroy to clean up resources like subscriptions before component is removed.Pass the test and this pattern moves unknown