In the section about components, we briefly mentioned life cycle hooks. Angular really makes it easy to plug in logic at different points in the life cycle of your applications/components (for example, when a component is created, rendered, or when it renders its children).
Using life cycle hooks is a breeze. All you need to do is implement the interface of the hook that you want to attach logic to.
Here's an example:
export class SomeComponent implements OnInit { constructor() { } // implement OnInit's method ngOnInit() { console.log('SomeComponent was just initialized'); } }
Here, we have used the OnInit life cycle hook, which requires us to implement the ngOnInit method. That method will be called each time this component gets initialized.
Here is a list of the most commonly used hooks:
- ngOnChanges: This allows you to react when input properties change.
- ngOnInit: This is called when Angular has initialized a component and has set its input properties.
- ngAfterContentInit: This allows you to react when external content has been projected into the component.
- ngAfterViewInit: This allows you to react once Angular has initialized the component's view.
- ngOnDestroy: This is called before Angular destroys the component/directive. This hook is very useful for performing cleanups (for example, unsubscribing from observables, which we'll soon learn about).