Skip to content

Instantly share code, notes, and snippets.

@mohanramphp
Last active March 22, 2020 04:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohanramphp/277b003a13184e251886b7ef5606b960 to your computer and use it in GitHub Desktop.
Save mohanramphp/277b003a13184e251886b7ef5606b960 to your computer and use it in GitHub Desktop.
Lifecycle hooks in angular
import {
Component,
OnInit,
OnChanges,
DoCheck,
AfterContentInit,
AfterContentChecked,
AfterViewInit,
AfterViewChecked,
OnDestroy
} from '@angular/core';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.css']
})
export class MapComponent
implements OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy {
// called during initialization of the component
constructor() {
console.log('constructor called');
}
// only called for/if there is an @Input variable set by parent.
ngOnChanges(changes: SimpleChanges) {
/**
{
[component input property]:{
previousValue: any,
currentValue: any,
firstChange: boolean,
isFirstChange(): boolean
}
}
*/
console.log('ngOnChanges called');
}
// called once component got initialized - think of it as post constructor
ngOnInit() {
console.log('ngOnInit called');
}
// Beware! Called frequently!
// Called in every change detection cycle anywhere on the page
ngDoCheck() {
console.log('ngDoCheck called');
}
// Called once angular projects the external content into the Component's view
ngAfterContentInit() {
console.log('ngAfterContentInit called');
}
// Beware! Called frequently!
// Called in every change detection cycle anywhere on the page
ngAfterContentChecked() {
console.log('ngAfterContentChecked called');
}
// Called once angular initializes the Component's view and its child component/directives view
ngAfterViewInit() {
console.log('ngAfterViewInit called');
}
// Beware! Called frequently!
// Called in every change detection cycle anywhere on the page
ngAfterViewChecked() {
console.log('ngAfterViewChecked called');
}
// called before angular destroys the component
ngOnDestroy() {
console.log('ngOnDestroy called');
}
}
// console output
// constructor called
// ngOnChanges called
// ngOnInit called
// ngDoCheck called
// ngAfterContentInit called
// ngAfterContentChecked called
// ngAfterViewInit called
// ngAfterViewChecked called
// ngDoCheck called
// ngAfterContentChecked called
// ngAfterViewChecked called
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment