Angular Lifecycle Hooks

Angular Lifecycle Hooks

A component has a lifecycle managed by Angular.

Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change, and destroys it before removing it from the DOM.

Angular offers lifecycle hooks that provide visibility into these key life moments and the ability to act when they occur.

A directive has the same set of lifecycle hooks.
Component lifecycle hooks overview

Directive and component instances have a lifecycle as Angular creates, updates, and destroys them. Developers can tap into key moments in that lifecycle by implementing one or more of the lifecycle hook interfaces in the Angular core library.

Each interface has a single hook method whose name is the interface name prefixed with ng. For example, the OnInit interface has a hook method named ngOnInit() that Angular calls shortly after creating the component:
peek-a-boo.component.ts (excerpt)

export class PeekABoo implements OnInit {
constructor(private logger: LoggerService) { }

// implement OnInit’s `ngOnInit` method
ngOnInit() { this.logIt(`OnInit`); }

logIt(msg: string) {
this.logger.log(`#${nextId++} ${msg}`);
}
}

No directive or component will implement all of the lifecycle hooks. Angular only calls a directive/component hook method if it is defined.

IT Professionals, Web Developers, Web Programmers, IT students can Apply for the certification course to move ahead in their careers.

Angular 4 Tutorial IndexBack to Angular 4 Tutorial Main Page

Share this post
[social_warfare]
Angular Dependency Injection
Angular Modules

Get industry recognized certification – Contact us

keyboard_arrow_up