wasAsked.

what is angular life cycle hook?

EY · Role not specified · technical

Published

Year not specified · Angular

Community answers

Posted by wasAsked editorial collection

Lifecycle hooks are methods Angular calls at specific moments in a component's or directive's life. Implementing them lets you run code at the right time. Order of the main hooks: 1. constructor — not a hook, but runs first. Use only for dependency injection and simple field initialisation; inputs are not set yet. 2. ngOnChanges(changes: SimpleChanges) — runs before ngOnInit and whenever an @Input reference changes. Use to react to input changes. 3. ngOnInit — runs once after the first ngOnChanges. Inputs are available; a good place to load data or set up subscriptions. 4. ngDoCheck — runs on every change detection cycle; for custom change detection. Use rarely, it is expensive. 5. ngAfterContentInit — once, after projected content (<ng-content>) is initialised; @ContentChild queries are ready. 6. ngAfterContentChecked — after every check of projected content. 7. ngAfterViewInit — once, after the component's view and child views are initialised; @ViewChild queries are ready, so you can access DOM elements or initialise third-party libraries. 8. ngAfterViewChecked — after every check of the view. 9. ngOnDestroy — just before Angular destroys the component. Unsubscribe, clear timers, remove listeners. Example: export class OrderDetailComponent implements OnInit, OnChanges, OnDestroy { @Input() orderId!: number; ngOnChanges(c: SimpleChanges) { if (c['orderId']) this.load(this.orderId); } ngOnInit() { this.timer = setInterval(() => this.refresh(), 30000); } ngOnDestroy() { clearInterval(this.timer); } } Modern additions - DestroyRef and takeUntilDestroyed() handle cleanup without ngOnDestroy. - afterNextRender and afterRender (afterEveryRender in newer versions) run code after the DOM renders, safely in server-side rendering. - With signals, computed() and effect() often replace ngOnChanges logic. Common mistakes: doing heavy work in ngDoCheck or the "Checked" hooks, changing bound data in ngAfterViewInit (causing ExpressionChangedAfterItHasBeenChecked errors), and forgetting cleanup in ngOnDestroy.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics