Understanding the Lifecycle
An Angular component has a lifecycle managed by the framework. From the moment it is instantiated to the moment it is destroyed, Angular provides 'hooks'—specific methods you can implement to tap into key moments. As a Technical Lead, mastering these hooks is essential for managing heavy resources like the Revochamp AI engine, ensuring you initialize data correctly and clean up memory to prevent leaks.
- Common Lifecycle Hooks
While there are many hooks, a few are used in almost every professional component. You implement these by adding the corresponding interface to your class and defining the method.
- ngOnChanges(): Responds when Angular sets or resets data-bound input properties (@Input). It receives a SimpleChanges object.
- ngOnInit(): Called once after the first ngOnChanges. This is the best place to fetch data from your Python APIs.
- ngOnDestroy(): Called just before Angular destroys the component. Use this to unsubscribe from Observables and stop timers.
- Implementation Example
- View & Content Hooks
Sometimes you need to interact with the DOM or child components. Hooks like ngAfterViewInit are triggered only after Angular has fully initialized the component's views and child views.
| Hook | Timing | Best Use Case |
|---|---|---|
| ngOnChanges | Before ngOnInit | Reacting to @Input changes |
| ngOnInit | After first OnChanges | Initial API calls / logic setup |
| ngDoCheck | Every change detection | Custom change detection logic |
| ngAfterViewInit | After view renders | Accessing @ViewChild elements |
| ngOnDestroy | Before destruction | Unsubscribing / memory cleanup |