Angular
Services & Dependency Injection
Create an injectable service and consume it in a component.
By EZ4Code Team
servicedependency-injection
Code
import { Injectable, inject, Component } from "@angular/core";
import { NgFor } from "@angular/common";
@Injectable({ providedIn: "root" })
export class UserService {
private users = ["Alice", "Bob"];
getAll() { return [...this.users]; }
add(name: string) { this.users.push(name); }
}
@Component({
selector: "app-user-list",
standalone: true,
imports: [NgFor],
template: "<li *ngFor=\"let u of users\">{{ u }}</li>"
})
export class UserListComponent {
private svc = inject(UserService);
users = this.svc.getAll();
}Explanation
Services encapsulate shared logic and state. The @Injectable decorator with providedIn root registers a singleton across the app. Components obtain instances via dependency injection using the inject() function or constructor parameters.
More Angular Snippets
Component Basics
Define an Angular component with selector, template, and styles.
Template Syntax & Binding
Interpolation, property, event, and two-way binding in Angular templates.
Built-in Directives
Use *ngIf, *ngFor, ngClass, and ngStyle to shape the DOM.
Pipes & Custom Pipe
Transform template values with built-in and custom pipes.
Routing Configuration
Define routes with params, lazy loading, and redirects.
Reactive Forms
Build a typed reactive form with FormBuilder and validators.