Learning

Component Lifecycle in Angular

component lifecycle

This article on Component Lifecyle in Angular is part of the Learning Angular series.

Understanding the Component Lifecycle

  1. ngOnChanges – Called after a bound input property changes. Called during initialization. Called multiple times.
  2. ngOnInit – Called when the component is initialized. it will run after the constructor
  3. ngDoCheck – Called during every change detection run
  4. ngAfterContentInit – Called after content (ng-content) has been projected into view
  5. ngAfterContentChecked – Called every time the projected component has been checked.
  6. ngAfterViewInit – Called after the components view and its children view has been initialized
  7. ngAfterViewChecked – Called every time the view and child views have been checked.
  8. ngOnDestroy – Called once the component is about to be destroyed.

Seeing Lifecycle Hooks in Action

While the Lifecycle functions can be called directly, it is better to ‘implement’ them on the component to be explicit about what functions are going to be accessed.

…
export class MyOwnComponent implements OnInit, OnChanges {
    ngOnInit() { }
    ngOnChanges(change:SimpleChange) { }
}

This is unchecked and can be rerun and noted down. TODO

Lifecycle Hooks and Template Access

If and any hook applied to templates and being accessed via the @Input() tag in the TypeScript file, the values are only available after the ngAfterViewInit() is called.

Getting Access to ng-content with @Content-Child

The template content that has been defined within the CustomComponent area to be projected into the ng-content area can also be accessed. This can be done by passing a hook #hookname, and can be accessed by using the Content-Child descriptor to access the ElementRef and use it after ngAfterContentInit() is called.

<app-cockpit>
    <p #theHook>
        …
    </p>
</app-cockpit>

And creating the reference in .ts file by using:

@ContentChild('theHook') element: ElementRef;

And access it after the ngAfterContentInit() is called:

this.element.nativeElement;

Leave a Reply

Your email address will not be published. Required fields are marked *