Angular

Last Updated: 9/4/2023

OnInit Interface

  • As a best practice constructor should be very small and light weight. We shouldn't perform expensive operations like calling server.
  • Components have life cycle hooks. They are special methods that we add to component and angular automatically call these methods at specific times during the Lifecyle of components.

Life Cycle Events

  • Creates a component
  • Renders it
  • Creates and renders its children
  • Destroys a component

Life Cycle Hooks

  • During the lifecycle events, angular will call specific methods in the component if they are defined
  • Lifecycle hooks
    • ngOnInit: a lifecycle hook called when angular initializes the component
    • ngOnChanges
    • ngDoCheck
    • ngAfterContentInit
  • Provides interface which declares method prefixed with ng. Implementing interface is optional. If we include it adds compile time checking.
  • Defining the hook method in the class is enough, angular will call the method automatically during the event.

ngOnInit and OnInit

  • Don't call http services in the constructor of the component
  • OnInit interface declares ngOnInit

Code

class PostsComponent implements Interface {
	ngOnInit() {
		//get data
	}	
}