Angular gives us 8 hooks to allow us to tap into the lifecycle of our components and trigger actions at specific points in the lifecycle.
This post discusses lifecycle hooks in Angular 2 and up.
Here are the lifecycle hooks available, in the order in which they are invoked:
Let’s give you a simple example using the ngOnInit hook. The ngOnInit lifecycle hook is probably the one you’ll use most often. If you have a lot of processing to do when the component gets created, it’s good practice to do it in the ngOnInit hook rather than in the constructor:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
constructor() {}
ngOnInit() {
this.setupData();
this.doStuff();
// ...
}
setupData() {
// ...
}
doStuff() {
// ...
}
}
Notice how we import OnInit, but we implement it with the ngOnInit method. It’s the same principle for the other lifecycle hooks.
Implementing multiple hooks is just as easy:
import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit, OnDestroy {
constructor() {}
ngOnInit() {
console.log('Component Init');
}
ngOnDestroy() {
console.log('Component Destroy');
}
}
The ngOnChanges hook, with it’s SimpleChanges object, is a little different. Here’s how you would implement it. Let’s say we have a component used like this:
<my-todo [title]="title" [content]="content"></my-todo>
Now say that we want to do something when the title property changes:
import { Component, Input, SimpleChanges, OnChanges }
from '@angular/core';
@Component({
// ...
})
export class MyTodoComponent implements OnChanges {
@Input() title: string;
@Input() content: string;
constructor() { }
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!