Dependency Injection (DI) is a pattern where Angular automatically delivers dependencies to components and services - like a supply system delivering weapons and provisions to castles.
1import { Component, inject } from '@angular/core';
2import { KatanaService } from './services/katana.service';
3
4@Component({
5 selector: 'app-forge',
6 standalone: true,
7 template: \`
8 <h2>Katana Forge</h2>
9 <button (click)="forgeKatana()">🔥 Forge a Katana</button>
10 <ul>
11 @for (katana of katanas; track katana.id) {
12 <li>{{ katana.name }} - {{ katana.damage }} DMG</li>
13 }
14 </ul>
15 \`
16})
17export class ForgeComponent {
18 private katanaService = inject(KatanaService);
19 katanas = this.katanaService.getAll();
20
21 forgeKatana(): void {
22 this.katanaService.forge('Masamune', 'Tachi');
23 this.katanas = this.katanaService.getAll();
24 }
25}1@Component({...})
2export class ForgeComponent {
3 constructor(private katanaService: KatanaService) {}
4
5 forgeKatana(): void {
6 this.katanaService.forge('Masamune', 'Tachi');
7 }
8}| Feature | inject() | Constructor | |---------|----------|-------------| | Syntax | Simpler | Standard | | Use in functions | Yes (with limitations) | No | | Inheritance | Easier | Requires super() | | Testing | Similar | Similar |