ngconf
Published in

ngconf

Angular Lifecycle Hooks

tldr;

Angular Lifecycle Hooks

  • ngOnChanges
  • ngOnInit
  • ngDoCheck
  • ngAfterContentInit
  • ngAfterContentChecked
  • ngAfterViewInit
  • ngAfterViewChecked
  • ngOnDestroy

ngOnInit

ngOnInit() {
this.results = this._dataService.getResults();
}

ngOnChanges

ngOnChanges(changes: SimpleChanges) {
this.total = this.inputOne + this.inputTwo;
}
{
"inputOne": {
"previousValue": 1,
"currentValue": 2,
"firstChange": false
}
}

ngAfterViewInit

export class DemoComponent implements AfterViewInit {
@ViewChild('myElement') myElement: ElementRef;
ngOnInit() {
console.log(this.myElement); // undefined
}
ngAfterViewInit() {
console.log(this.myElement); // ElementRef { ... }
}
}

ngOnDestroy

private subscription;ngOnInit() {
this.subscription = this.someService.appState.pipe().subscribe();
}
ngOnDestroy() {
this.subscription.unsubscribe();
}

Conclusion

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store