Angular Series: Key Concepts in a Flash
This blog is the first in the Angular Concepts series . We will explore many other concepts such as Dependency Injection, Data Binding, Router, Services, and much more. If you are a beginner, this will aid you in your journey to learn Angular.
Coding for each instance requires a means of detection. Lifecycle hooks answer this need. Modern front-end frameworks package themselves with a variety of lifecycle hooks. Angular is no exception.
ngOnInit and constructor methods in Angular might be confusing to you ? Why should ngOnInit
be used, if we already have a constructor
?
What is a Constructor?
A constructor is a special method which will be called whenever we create new objects. And it is responsible for setting up the Angular environment. The constructor can be used to inject dependencies, set the default values for properties, and run any other initialization code that is needed.
Here's an example that demonstrates the use of a constructor in an Angular component for injecting dependencies, such as a service using Dependency Injection.
import { Component } from '@angular/core';
import { DataService } from './data.service'; // Importing the DataService
@Component({
selector: "app-example",
template: "<h1>{{title}}</h1>"
})
export class ExampleComponent {
title: string;
// Constructor method with dependency injection
constructor(private dataService: DataService) {}
this.title = "Angular";
}
}
This constructor initializes the component's properties title
and injects the DataService
dependency when an instance of the component is created.
- ✍It’s better to avoid writing actual work in the constructor.
- ✍The constructor() should only be used to initialize class members but shouldn’t do actual “work”.
- ✍So, we should use constructor() to setup Dependency Injection, Initialization of class fields etc.
What is ngOnInit() in Angular?
ngOnInit
is a lifecycle hook in Angular, allowing you to tap into the lifecycle of directives and components as they are created, updated, and destroyed. It's defined by the OnInit
interface, which Angular utilizes to execute initialization logic.
Angular provides a set of lifecycle hooks, each represented by an interface with a single hook method. For example, ngOnChanges
is part of the OnChanges
interface.
ng
.These hooks are invoked by Angular in a specific order as follows:
ngOnChanges
: Invoked after Angular sets data-bound input properties.ngOnInit
: Invoked once, after the firstngOnChanges
.ngDoCheck
: Invoked during every change detection run.ngAfterContentInit
: Invoked after Angular projects external content into the component's view.ngAfterContentChecked
: Invoked after Angular checks the content projected into the component.ngAfterViewInit
: Invoked after Angular initializes the component's views and child views.ngAfterViewChecked
: Invoked after Angular checks the component's views and child views.ngOnDestroy
: Invoked just before Angular destroys the component.
OnInit
interface from @angular/core
.Here is an example :
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service'; // Importing the DataService
@Component({
selector: 'app-example',
template: <p>Data: {{data}}</p>
})
export class ExampleComponent {
data: any;
constructor(private dataService: DataService) {}
ngOnInit() {
// Accessing the injected service to fetch data
this.data = this.dataService.getData();
}
}
Let's summarize!
The constructor
, a default method inherent to TypeScript classes, isn't directly tied to Angular. Generally, it's employed for variable initialization or basic setup tasks. Yet, Angular-specific tasks, such as initializing bindings, are better suited for Angular's ngOnInit
lifecycle hook. ngOnInit
is specifically designed for Angular-centric initialization activities and is called promptly after the constructor, aligning well with Angular's lifecycle flow.
👋 Thanks for reading! For the next blog post, we'll be diving into Dependency Injection (DI) in Angular. Stay tuned as we explore this fundamental concept in Angular development.
Subscribe to my newsletter
Read articles from Meriem Trabelsi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Meriem Trabelsi
Meriem Trabelsi
I am a curious, ambitious young woman passionate about the IT world 🙂. Acutually, I am software Engineering Student @ISI. More motivated to discover new technologies. I am interested in project management and the different approaches, business intelligence, web/mobile development, ISTQB (software testing) and so on ..