Angular API Reference & Cheatsheet
Complete Angular API reference covering decorators, lifecycle hooks, Signals, directives, pipes, forms, routing, HTTP client, and CLI commands. Use this as a quick lookup while building Angular applications with DodaTech’s frameworks.
What You’ll Learn
- Quick syntax reference for all Angular decorators, directives, and APIs
- Common code patterns for forms, routing, and HTTP
- RxJS operator overview for service development
- CLI commands for daily development workflow
Why This Reference Matters
When you’re deep in development — debugging a form, wiring up a route, or fixing a service — you don’t need a tutorial. You need a quick lookup. This reference is designed to get you the syntax and patterns you need in seconds. Bookmark it, print it, or keep it open in a tab while you code.
Security note: Understanding Reference helps build more secure applications — a core principle at DodaTech, where tools like Durga Antivirus Pro and Doda Browser rely on solid implementation practices.
flowchart LR
A["All Angular Tutorials"] --> B["**Angular Reference**"]
B --> C["Real-World Angular Projects"]
style B fill:#f97316,stroke:#c2410c,color:#fff
Installation & Quick Start
npm install -g @angular/cli
ng new my-app --standalone --routing
ng serve # Dev server at localhost:4200
ng generate component name # Create a component
ng generate service name # Create a service
ng generate pipe name # Create a pipe
ng build # Production buildDecorators
| Decorator | Purpose |
|---|---|
@Component() | Defines a component with template, styles, selector |
@Directive() | Creates an attribute or structural directive |
@Pipe() | Defines a custom template transformation |
@Injectable() | Marks a class for dependency injection |
@Input() | Receives data from a parent component |
@Output() | Emits events to a parent component |
@ViewChild() | Queries a child component or DOM element |
@ContentChild() | Queries projected content from a parent |
@HostBinding() | Binds to a property on the host element |
@HostListener() | Listens to events on the host element |
// Example: @Input and @Output
@Input() name: string = "";
@Output() voted = new EventEmitter<string>();Lifecycle Hooks
constructor → ngOnChanges → ngOnInit → ngDoCheck →
ngAfterContentInit → ngAfterContentChecked →
ngAfterViewInit → ngAfterViewChecked → ngOnDestroy| Hook | When to Use |
|---|---|
ngOnChanges | React to @Input property changes |
ngOnInit | Fetch data, initialize state, set up subscriptions |
ngDoCheck | Custom change detection logic |
ngAfterViewInit | Access ViewChildren (like @ViewChild) |
ngOnDestroy | Cleanup subscriptions, timers, event listeners |
Signals (Angular 17+)
import { signal, computed, effect, input, output } from "@angular/core";
// Create signals
const count = signal(0); // Writable signal
const double = computed(() => count() * 2); // Derived (read-only)
// Update
count.set(5); // Replace value
count.update(v => v + 1); // Derive from current
// Side effects
effect(() => console.log(count())); // Runs when deps change
// Signal inputs/outputs in components
name = input.required<string>(); // Required signal input
age = input(0); // Optional with default
greeted = output<string>(); // Output signal
Data Binding
{{ value }} <!-- Interpolation (string output) -->
[property]="expr" <!-- Property binding (preserves type) -->
(event)="handler($event)" <!-- Event binding -->
[(ngModel)]="value" <!-- Two-way binding (needs FormsModule) -->
[class.active]="isActive" <!-- Class binding -->
[style.color]="color" <!-- Style binding -->Directives
Structural (DOM structure)
<!-- Legacy syntax -->
*ngIf="condition"
*ngFor="let item of items; trackBy: trackFn"
*ngSwitch="value"; *ngSwitchCase="'a'"; *ngSwitchDefault
<!-- Modern syntax (Angular 17+) -->
@if (condition) { } @else { }
@for (item of items; track item.id) { } @empty { }
@switch (value) { @case ('a') { } @default { } }Attribute (appearance/behavior)
[ngClass]="{ active: flag, error: hasError }"
[ngStyle]="{ color: 'red', fontSize: '14px' }"Built-in Pipes
{{ date | date:'short' }} <!-- 6/6/26, 12:00 PM -->
{{ num | number:'1.2-2' }} <!-- 1,234.56 -->
{{ price | currency:'USD' }} <!-- $19.99 -->
{{ text | uppercase }} <!-- HELLO -->
{{ text | lowercase }} <!-- hello -->
{{ text | titlecase }} <!-- Hello World -->
{{ text | slice:0:100 }} <!-- First 100 chars -->
{{ obj | json }} <!-- { "key": "value" } -->
{{ 0.95 | percent }} <!-- 95% -->
{{ observable$ | async }} <!-- Auto-subscribe -->Forms
Template-Driven
<form #f="ngForm" (ngSubmit)="submit(f)">
<input name="email" ngModel required email #email="ngModel" />
<div *ngIf="email.invalid && email.touched">Error</div>
</form>Module: FormsModule. Import in your standalone component’s imports array.
Reactive
import { FormBuilder, Validators, FormGroup, FormArray } from "@angular/forms";
// Create form group
fb.group({
name: ["", Validators.required],
email: ["", [Validators.required, Validators.email]],
addresses: fb.array([]) // Dynamic array
});Module: ReactiveFormsModule.
Validators
Validators.required // Field must have value
Validators.requiredTrue // Checkbox must be checked
Validators.email // Valid email format
Validators.minLength(6) // Min characters
Validators.maxLength(100) // Max characters
Validators.min(18) // Min numeric value
Validators.max(120) // Max numeric value
Validators.pattern(/^[a-z]+$/) // Regex pattern
Form State
| Property | Meaning |
|---|---|
control.valid | No validation errors |
control.invalid | Has validation errors |
control.touched | Field was focused and blurred |
control.dirty | User changed the value |
control.pristine | Value unchanged |
control.pending | Async validation in progress |
control.errors | Object of validation errors |
Router
import { provideRouter, Routes } from "@angular/router";
// Route configuration
const routes: Routes = [
{ path: "", component: HomeComponent, title: "Home" },
{ path: "products/:id", component: ProductDetailComponent, title: "Detail" },
{
path: "admin",
loadComponent: () => import("./admin.component"),
canActivate: [authGuard]
},
{ path: "**", component: NotFoundComponent } // 404 — must be last
];
// Provide in app.config.ts
providers: [provideRouter(routes)];Navigation
import { Router, ActivatedRoute } from "@angular/router";
// Programmatic navigation
router.navigate(["/products", id]); // Absolute
router.navigate(["edit"], { relativeTo: route }); // Relative
router.navigateByUrl("/about"); // By URL string
router.navigate(["/search"], { queryParams: { q: "angular" } });
// Reading params
route.paramMap.subscribe(p => p.get("id"));
route.queryParamMap.subscribe(q => q.get("q"));
// Snapshot (initial value only)
route.snapshot.paramMap.get("id");Template
<a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">Home</a>
<router-outlet />Guards
canActivate: [authGuard] // Before entering route
canActivateChild: [authGuard] // Before entering child route
canDeactivate: [unsavedGuard] // Before leaving route
canMatch: [featureGuard] // Before matching route
HTTP Client
import { provideHttpClient, withInterceptors } from "@angular/common/http";
// In app.config.ts
providers: [provideHttpClient(withInterceptors([authInterceptor]))];
// HTTP methods
http.get<T>(url, { params, headers });
http.post<T>(url, body);
http.put<T>(url, body);
http.patch<T>(url, body);
http.delete<T>(url);Interceptors
import { HttpInterceptorFn } from "@angular/common/http";
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = localStorage.getItem("token");
const cloned = token
? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } })
: req;
return next(cloned);
};RxJS Quick Reference
import { Observable, of, from, Subject, BehaviorSubject,
forkJoin, combineLatest } from "rxjs";
import { map, filter, tap, switchMap, catchError, debounceTime,
distinctUntilChanged, takeUntil, retry } from "rxjs/operators";
// Common pattern: search with debounce
obs$.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap(val => http.get(`/api?q=${val}`)),
catchError(err => of([])),
tap(console.log)
).subscribe({ next: handler, error: handler });CLI Commands
ng serve # Start dev server
ng build # Production build
ng test # Unit tests (Karma)
ng e2e # End-to-end tests
ng generate component <name> # ng g c
ng generate service <name> # ng g s
ng generate pipe <name> # ng g p
ng generate directive <name> # ng g d
ng generate guard <name> # ng g g
ng generate interceptor <name>
ng add @angular/material # Add Angular Material
ng update # Update Angular & depsCommon Imports
// Core
import { Component, OnInit, signal, input, output, computed, effect,
ViewChild, ContentChild, ElementRef, ChangeDetectionStrategy,
ViewEncapsulation } from "@angular/core";
// Forms
import { FormBuilder, FormGroup, FormArray, FormControl,
Validators, FormsModule, ReactiveFormsModule } from "@angular/forms";
// HTTP
import { HttpClient, HttpParams, HttpHeaders,
HttpInterceptorFn, provideHttpClient, withInterceptors } from "@angular/common/http";
// Router
import { Router, ActivatedRoute, RouterModule,
provideRouter, Routes } from "@angular/router";
// Common
import { CommonModule } from "@angular/common";App Config Template
// app.config.ts
import { ApplicationConfig } from "@angular/core";
import { provideRouter } from "@angular/router";
import { provideHttpClient, withInterceptors } from "@angular/common/http";
import { provideAnimations } from "@angular/platform-browser/animations";
import { provideClientHydration } from "@angular/platform-browser";
import { routes } from "./app.routes";
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(withInterceptors([])),
provideAnimations(),
provideClientHydration()
]
};Common Mistakes
1. Importing from wrong module
FormsModule vs ReactiveFormsModule — they’re different. Template-driven forms need FormsModule. Reactive forms need ReactiveFormsModule.
2. Forgetting HttpClient provider
Without provideHttpClient() in app config, injecting HttpClient throws a null injector error.
3. Using *ngIf and @if together in older Angular versions
@if syntax requires Angular 17+. Stick to one style per project.
4. Confusing paramMap snapshot vs Observable
Snapshot is one-time. Observable reacts to changes. Use Observable when the component can receive different params without re-creating.
5. Missing trackBy or track in loops
Performance degrades significantly on large lists without a tracking function.
6. Not resetting forms after submit
Call form.reset() after successful submission to clear values and validation state.
Practice Questions
What decorator would you use to listen for a click on the host element?
@HostListener("click")on a method in a directive or component.What’s the difference between
BehaviorSubjectandSubject?BehaviorSubjectrequires an initial value and emits the current value to new subscribers.Subjecthas no initial value and only emits future values.Which pipe automatically unsubscribes from an Observable? The
asyncpipe. It subscribes in the template and unsubscribes when the component is destroyed.What does
path: "**"mean in route configuration? It’s a wildcard that matches any URL not matched by previous routes. Used for 404 pages. Must be the last route.How do you provide a value instead of a class in DI? Use
InjectionTokenwith{ provide: MY_TOKEN, useValue: "my-value" }.
Challenge
Using this reference only, build a complete Angular component that: displays a list from an API using HttpClient, has a search input with debounce, uses reactive forms, and navigates to a detail page on item click.
FAQ
Try It Yourself
Keep this reference open while you build a small Angular app. Try to complete each task using only the reference above without looking at tutorials:
- Create a new Angular project
- Generate a component, service, and pipe
- Set up routing with 3 routes (one lazy-loaded)
- Build a reactive form with validation
- Create an HTTP service with error handling
- Add an interceptor for logging
What’s Next
| Tutorial | Description |
|---|---|
| https://tutorials.dodatech.com/frameworks/angular/angular-basics/ | Start learning Angular from the beginning |
| https://tutorials.dodatech.com/frameworks/angular/angular-advanced/ | Signals, OnPush, dynamic components, SSR |
| https://tutorials.dodatech.com/frameworks/angular/material/ | Angular Material UI component library |
Related topics: TypeScript, RxJS, JavaScript.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro