Monday, May 25, 2020

Angular component Lifecycle Hooks

Lifecycle Hooks

  1. ngOnChanges()
    • Used in pretty much any component that has an input.
    • Called whenever an input value changes
    • Is called the first time before ngOnInit
  2. ngOnInit()
    • Used to initialize data in a component.
    • Called after input values are set when a component is initialized.
    • Added to every component by default by the Angular CLI.
    • Called only once
  3. ngDoCheck()
    • Called during all change detection runs
      • A run through the view by Angular to update/detect changes
  4. ngAfterContentInit()
    • Called only once after first ngDoCheck()
    • Called after the first run through of initializing content
  5. ngAfterContentChecked()
    • Called after every ngDoCheck()
    • Waits till after ngAfterContentInit() on first run through
  6. ngAfterViewInit()
    • Called after Angular initializes component and child component content.
    • Called only once after view is initialized
  7. ngAfterViewChecked()
    • Called after all the content is initialized and checked. (Component and child components).
    • First call is after ngAfterViewInit()
    • Called after every ngAfterContentChecked() call is completed
  8. ngOnDestroy()
    • Used to clean up any necessary code when a component is removed from the DOM.
      • Fairly often used to unsubscribe from things like services.
    • Called only once just before component is removed from the DOM.