Angular - 5.14-Understanding the component life cycle
Every Angular component goes through a well-defined lifecycle that starts when the framework instantiates the class and ends when the component is destroyed. By implementing the matching lifecycle interfaces, you can hook into any of those moments and run custom logic at the right time.
The main lifecycle hooks
ngOnChanges— runs whenever an@Input()property receives a new value. Receives aSimpleChangesobject with the previous and current values.ngOnInit— runs once, right after the firstngOnChanges. Ideal place to fetch data and initialise state.ngDoCheck— runs on every change detection cycle. Use sparingly to avoid performance issues.ngAfterContentInit/ngAfterContentChecked— when projected content (ng-content) has been initialised or checked.ngAfterViewInit/ngAfterViewChecked— when the component's own view is ready or has been checked.@ViewChildreferences are safe to use here.ngOnDestroy— runs right before Angular removes the component. The right place to unsubscribe from observables and clean up.
Implementing a hook is as simple as declaring a method with the matching name on the class. For TypeScript safety it is recommended to also implement the corresponding interface (OnInit, OnDestroy, …) imported from @angular/core. That way the compiler catches typos and signature mismatches.
export class ServerComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log('Server component initialised');
}
ngOnDestroy() {
console.log('Server component destroyed');
}
}
Most components only need ngOnInit and ngOnDestroy in practice. The rest of the hooks are powerful tools to keep in your back pocket for advanced scenarios such as integrating non-Angular libraries, reacting to projected content changes, or implementing custom change detection strategies.