Angular Documentation
Google's complete TypeScript framework — components, templates, services, dependency injection, RxJS, routing and forms.
Angular is Google's full framework for large web apps, written in TypeScript. Routing, forms, HTTP and testing all come built in, which is why many companies, especially in enterprise and service work, use it. This page uses modern Angular: standalone components, signals and the new control flow.
1. Introduction
| Piece | What it does |
|---|---|
| Component | A class + template: one part of the screen |
| Template | HTML with Angular syntax |
| Signal | A reactive value |
| Service | Shared logic and data calls |
| Dependency injection | Angular hands classes the services they need |
| Router | Pages |
| RxJS | Streams of async values, used by HTTP and forms |
2. Setup
npm install -g @angular/cli
ng new my-app
cd my-app
ng serve --open # http://localhost:4200
ng generate component student-card
ng generate service students
3. Your First Component
import { Component, signal, computed } from '@angular/core';
@Component({
selector: 'app-counter',
template: `
<h1>Count: {{ count() }}</h1>
<p>Double: {{ double() }}</p>
<button (click)="add()">Add</button>
`,
styles: `h1 { color: teal; }`,
})
export class CounterComponent {
count = signal(0);
double = computed(() => this.count() * 2);
add() {
this.count.update((n) => n + 1);
}
}
Read a signal by calling it: count(). Change it with set or update.
4. Template Syntax
<!-- interpolation, property and event binding -->
<h2>{{ title }}</h2>
<img [src]="photo" [alt]="name" />
<button [disabled]="busy()" (click)="save()">Save</button>
<!-- classes -->
<div [class.active]="isActive()"></div>
<!-- control flow -->
@if (marks() >= 40) {
<p>Pass</p>
} @else {
<p>Fail</p>
}
@for (s of students(); track s.id) {
<li>{{ s.name }}</li>
} @empty {
<li>No students yet</li>
}
<!-- pipes format values -->
<p>{{ today | date: 'dd MMM yyyy' }}</p>
<p>{{ price | currency: 'INR' }}</p>
Older code uses *ngIf and *ngFor; the @if and @for blocks replace them.
5. Inputs and Outputs
import { Component, input, output } from '@angular/core';
@Component({
selector: 'app-student-card',
template: `
{{ name() }} — {{ marks() }}
<button (click)="remove.emit(name())">Remove</button>
`,
})
export class StudentCardComponent {
name = input.required<string>();
marks = input(0);
remove = output<string>();
}
<app-student-card name="Asha" [marks]="91" (remove)="onRemove($event)" />
Import a component into the imports array of the component that uses it.
6. Services and Dependency Injection
import { Injectable, inject, signal } from '@angular/core';
import { HttpClient } from '@angular/common/http';
export interface Post { id: number; title: string; }
@Injectable({ providedIn: 'root' }) // one shared instance for the whole app
export class PostService {
private http = inject(HttpClient);
getPosts() {
return this.http.get<Post[]>('https://jsonplaceholder.typicode.com/posts');
}
}
Enable HTTP once, in app.config.ts:
export const appConfig = {
providers: [provideRouter(routes), provideHttpClient()],
};
7. Using HTTP in a Component
@Component({
selector: 'app-posts',
template: `
@if (error()) {
<p>{{ error() }}</p>
}
@for (p of posts(); track p.id) {
<li>{{ p.title }}</li>
}
`,
})
export class PostsComponent implements OnInit {
private service = inject(PostService);
posts = signal<Post[]>([]);
error = signal('');
ngOnInit() {
this.service.getPosts().subscribe({
next: (data) => this.posts.set(data),
error: (e) => this.error.set(e.message),
});
}
}
HTTP calls return Observables: nothing happens until you subscribe.
8. RxJS Essentials
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs';
this.searchBox.valueChanges.pipe(
debounceTime(300), // wait for typing to pause
distinctUntilChanged(), // skip repeats
switchMap((q) => this.api.search(q)), // cancel the older request
).subscribe((results) => this.results.set(results));
| Operator | Does |
|---|---|
map |
Transform each value |
filter |
Keep some values |
switchMap |
Move to a new stream, cancelling the old one |
debounceTime |
Wait for a pause |
catchError |
Handle errors |
Common mistake: a manual
subscribethat is never ended leaks memory. UsetakeUntilDestroyed(), or theasyncpipe in templates.
9. Routing
export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'courses/:id', component: CourseComponent },
{ path: 'admin', loadComponent: () => import('./admin').then((m) => m.AdminComponent), canActivate: [authGuard] },
{ path: '**', component: NotFoundComponent },
];
<a routerLink="/courses/7">Open</a>
<router-outlet />
loadComponent lazy-loads a page. A guard decides whether a route may open.
10. Forms
Reactive forms are the usual choice for real apps:
form = inject(FormBuilder).group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(8)]],
});
submit() {
if (this.form.valid) console.log(this.form.value);
}
<form [formGroup]="form" (ngSubmit)="submit()">
<input formControlName="email" />
@if (form.controls.email.invalid && form.controls.email.touched) {
<small>Enter a valid email</small>
}
<button [disabled]="form.invalid">Save</button>
</form>
11. Lifecycle and Interceptors
| Hook | Runs |
|---|---|
ngOnInit |
Once, after inputs are set; fetch data here |
ngOnChanges |
When an input changes |
ngOnDestroy |
Before removal; clean up here |
An HTTP interceptor changes every request, for example to add a login token:
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = localStorage.getItem('token');
return next(token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req);
};
12. Practice Problems
- A counter with signals and a computed double.
- A to-do app with
@for, add, delete and a filter. - A service that loads posts, with loading and error states.
- A search box using
debounceTimeandswitchMap. - A login form with validation, a route guard and an interceptor.
13. Interview Questions
What is dependency injection? Angular creates services and passes them to the classes that need them, which keeps code loosely coupled and easy to test.
Observable vs Promise? A Promise gives one value and starts at once; an Observable can give many values, starts on subscribe, and can be cancelled.
What are signals? Reactive values that tell Angular exactly what to update.
What does change detection do? It keeps the screen in sync with the data. OnPush and signals reduce unnecessary checks.
switchMap vs mergeMap? switchMap cancels the previous inner stream; mergeMap runs them all together.
Template-driven vs reactive forms? Template-driven is simple and lives in the HTML; reactive is defined in code and is easier to test.
What is a route guard? A function that allows or blocks navigation.
What is lazy loading? Downloading a page's code only when it is opened.
What is an interceptor? Code that handles every HTTP request or response in one place.
14. Cheat Sheet & References
CLI
ng new app
ng serve
ng generate component name
ng generate service name
ng build
ng test
Signals and components
count = signal(0);
count(); count.set(1); count.update((n) => n + 1);
double = computed(() => this.count() * 2);
name = input.required<string>();
saved = output<string>();
service = inject(MyService);
Templates
{{ value }}
<img [src]="url" />
<button (click)="go()"></button>
@if (ok()) { } @else { }
@for (x of list(); track x.id) { }
{{ price | currency: 'INR' }}