Mastering the Angular Component Lifecycle
In Angular, a component isn't just a static block of code. It is a living entity that is created, updated, and destroyed. Angular exposes key moments in this process via Lifecycle Hooks. Understanding these hooks is what separates a beginner from an expert who can write efficient, bug-free code.
The "Big Three": Constructor vs. OnInit vs. OnDestroy
One of the most common interview questions and sources of confusion is:"Why use ngOnInit if we have a constructor?"
Constructor
- A standard TypeScript feature (not Angular specific).
- Called when the class is instantiated.
- Use only for Dependency Injection.
- Inputs (@Input) are undefined here.
ngOnInit
- Specific to Angular.
- Called after the first `ngOnChanges`.
- Use for logic and data fetching.
- Inputs are available and ready to use.
Navigating the View: ngAfterViewInit
Sometimes you need to interact directly with the DOM (e.g., drawing on a Canvas or initializing a jQuery plugin). You cannot do this in `ngOnInit` because the template hasn't been rendered yet.
ngAfterViewInit is the hook for this. It guarantees that the component's view and its children's views are fully initialized. However, be warned: modifying data bound properties here will trigger the infamous ExpressionChangedAfterItHasBeenCheckedError, because Angular has already completed its change detection cycle for the view.
The Silent Killer: Memory Leaks
Single Page Applications (SPAs) stay loaded in the browser for a long time. If you subscribe to an Observable (like a timer or a global state service) and don't unsubscribe, that subscription keeps running even after the user navigates away.
Key Takeaway: Always implement theOnDestroyinterface and put your cleanup logic (unsubscribing, detaching event listeners) insidengOnDestroy(). This ensures your app stays fast and doesn't crash the browser over time.