This content originally appeared on DEV Community and was authored by Ankur Singh
Introduction
Welcome to this blog. In this blog, we will be learning how the Angular DI(Dependency Injection) works by creating the Injectable Services and using them inside our components throughout the application. We’ll be creating the popular Hogwarts Sorting Hat using the DI(Dependency Injection).
Are you ready? If yes, write gryffindor
Angular Component
Angular Components are responsible for the view that is shown to the user interface. The component task is to take care of User Experience and nothing more.
In simple terms, if you are visiting a web application, two things are happening underneath the hood: you are seeing what you need to see, the UI, and the web app is doing the business part, fetching the data from the server, cleaning it, formatting it, sometimes some calculation and so on.
So our components are responsible for showing the User Interface(data) to the user, and our Services are responsible for doing the other part I mentioned above.
Angular Dependency Injection(DI)
In Angular, the DI system comprises the dependency consumer, dependency provider & Injector
. We didn’t need to delve too deeply into the concepts of dependency consumer and provider.
All we need to know about dependency can be visualised as something we rely on [ like Harry Potter relies on their wand to cast the spell ].
Dependency consumer is who is requesting the dependency(data, function, property), Dependency Provider is who is providing these things and Injector
helps to facilitate the interaction between dependency consumers and dependency providers.
Let’s code it
1 First, make a new Angular Project
Run this script make sure you have Angular CLI installed.
ankur@ankur:~$ ng new learn-services
2 Then make the server run
learn-services$ npm start
3 Configure the project
- Go to app.html file remove everything expect this line
<router-outlet />
-
Create a new component
learn-services$ ng generate component components/main-page
-
Create a new service
learn-services$ ng generate service services/sorting-hat
4 Let’s write some HTML Code in components/main-page.html
<div class="sorting-hat-container">
<h2>🧙♂ Hogwarts Sorting Hat</h2>
<p>Enter your name to discover your Hogwarts House!</p>
<input type="text" [(ngModel)]="userName" placeholder="Type your name..." class="name-input" />
<button (click)="sorting_hat(userName)" class="sort-btn">Sort Me!</button>
@if(houseName){
<div class="result">
<h3>Congratulations, {{userName}}!</h3>
<p>You belong to <span class="house">{{houseName}}</span>!</p>
</div>
}
</div>
the CSS in components/main-page.css
.sorting-hat-container {
max-width: 400px;
margin: 40px auto;
padding: 24px;
background: #f8f4e3;
border-radius: 16px;
box-shadow: 0 4px 16px rgba(0,0,0,0.12);
text-align: center;
font-family: 'Segoe UI', 'Arial', sans-serif;
}
.name-input {
padding: 8px;
width: 80%;
margin-bottom: 16px;
border-radius: 8px;
border: 1px solid #bfa76f;
font-size: 1rem;
}
.sort-btn {
background: #7f5a36;
color: #fff;
border: none;
padding: 10px 24px;
border-radius: 8px;
font-size: 1rem;
cursor: pointer;
transition: background 0.2s;
}
.sort-btn:hover {
background: #a67c52;
}
.result {
margin-top: 24px;
background: #fffbe6;
padding: 16px;
border-radius: 8px;
border: 1px solid #bfa76f;
}
.house {
font-weight: bold;
color: #7f5a36;
font-size: 1.2em;
}
5 Now time to create the service and inject it inside our component
Open services/sorting-hat.ts
and paste this
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SortingHat {
houses: string[] = ['Gryffindor', 'Hufflepuff', 'Ravenclaw', 'Slytherin'];
sorting_hat(){
let index = Math.floor(Math.random() * (4 - 1 + 1)) + 1;
return this.houses[index];
}
}
It’s basically a function which helps in sorting the students.
6 Inject services into the component
It’s very easy, this one line is at all.
sortingFunction = inject(SortingHat);
7 Here is the full code of the main-page.ts file
import { Component, inject } from '@angular/core';
import { SortingHat } from '../../services/sorting-hat';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-main-page',
imports: [FormsModule],
templateUrl: './main-page.html',
styleUrl: './main-page.css'
})
export class MainPage {
userName: string = '';
houseName: string = '';
sortingFunction = inject(SortingHat);
sorting_hat(name: string): void {
this.houseName = this.sortingFunction.sorting_hat();
}
}
Time to refresh the page
Nothing happens 😉 Because we have not bound our main HTML file app.html yet.
Go to app.ts
file
...
import { MainPage } from './components/main-page/main-page';
...
imports: [RouterOutlet, MainPage],
...
Go to app.html
file
<app-main-page />
<router-outlet />
Time to refresh the page again.
You nailed it
You have learned how to create your injectable services and inject with in different components and reuse it. I have share the code repository here for your reference.
Reference
Email: ankursingh91002@gmail.com
LinkedIn: Ankur Singh
Twitter: @ankur_136
Let’s connect and create something great together!
This content originally appeared on DEV Community and was authored by Ankur Singh