Angular Tutorial for Beginners – Complete Guide
Angular basics, setup, components, templates, routing, forms, HTTP and Signals.
Learn Angular step by step: setup, components, data binding, directives, services, routing, forms, HTTP and Signals – with ready-to-copy code examples.
Angular is a free, open-source front-end framework developed by Google for building fast, scalable single-page applications (SPAs). It uses TypeScript and gives you everything out of the box: components, routing, forms, HTTP client, testing tools and a powerful CLI.
| Feature | Benefit |
|---|---|
| Component-based | Reusable, testable UI blocks |
| TypeScript | Strong typing & better tooling |
| Dependency Injection | Clean, maintainable services |
| Angular CLI | Generate, build, test with one command |
| Signals | Fine-grained, fast reactivity |
Install Node.js (LTS version) first, then install the Angular CLI globally:
npm install -g @angular/cli
ng version
# create a new project
ng new my-first-app
cd my-first-app
ng serve --openhttp://localhost:4200 and reloads automatically when you save a file.Important project files:
src/main.ts – entry point that bootstraps the appsrc/app/app.component.ts – root componentsrc/app/app.routes.ts – route definitionsangular.json – workspace/build configurationA component = TypeScript class + HTML template + CSS styles. Generate one with the CLI:
ng generate component helloimport { Component } from '@angular/core';
@Component({
selector: 'app-hello',
standalone: true,
template: `<h2>Hello, {{ name }}!</h2>`,
styles: [`h2 { color: #dd0031; }`]
})
export class HelloComponent {
name = 'A143MK Readers';
}Use it in any template: <app-hello></app-hello>
Angular supports four types of data binding. Click the tabs:
<p>Welcome {{ userName }}</p><img [src]="imageUrl" [alt]="title">
<button [disabled]="isLoading">Save</button><button (click)="sayHello()">Click Me</button><!-- import FormsModule in the component -->
<input [(ngModel)]="userName">
<p>Hello {{ userName }}</p>Hello, Guest 👋
Modern Angular (v17+) uses the built-in control flow syntax @if, @for and @switch:
@if (isLoggedIn) {
<p>Welcome back!</p>
} @else {
<button (click)="login()">Login</button>
}
<ul>
@for (item of items; track item.id) {
<li>{{ item.name }}</li>
} @empty {
<li>No items found</li>
}
</ul>Attribute directives change appearance or behaviour:
<div [class.active]="isActive" [style.color]="textColor">Styled text</div>*ngIf and *ngFor still works, but the new control flow is faster and recommended.import { Component, input, output } from '@angular/core';
@Component({
selector: 'app-product',
standalone: true,
template: `
<h3>{{ title() }}</h3>
<button (click)="buy.emit(title())">Buy</button>
`
})
export class ProductComponent {
title = input.required<string>(); // data IN from parent
buy = output<string>(); // event OUT to parent
}<app-product [title]="'Laptop'" (buy)="onBuy($event)" />Services hold shared logic and data. Angular injects them wherever needed.
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class TodoService {
private todos: string[] = ['Learn Angular', 'Read A143MK blog'];
getAll() { return this.todos; }
add(todo: string) { this.todos.push(todo); }
}import { Component, inject } from '@angular/core';
import { TodoService } from './todo.service';
@Component({ selector: 'app-todos', standalone: true, template: `...` })
export class TodosComponent {
private todoService = inject(TodoService);
todos = this.todoService.getAll();
}import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
export const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'user/:id', loadComponent: () =>
import('./user/user.component').then(m => m.UserComponent) },
{ path: '**', redirectTo: '' }
];<nav>
<a routerLink="/" routerLinkActive="active">Home</a>
<a routerLink="/about">About</a>
</nav>
<router-outlet />loadComponent enables lazy loading – the code is downloaded only when the route is visited.import { Component, inject } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-login',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="submit()">
<input formControlName="email" placeholder="Email">
<input formControlName="password" type="password">
<button [disabled]="form.invalid">Login</button>
</form>
`
})
export class LoginComponent {
private fb = inject(FormBuilder);
form = this.fb.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(6)]]
});
submit() { console.log(this.form.value); }
}import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes), provideHttpClient()]
};import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
export interface Post { id: number; title: string; }
@Injectable({ providedIn: 'root' })
export class PostService {
private http = inject(HttpClient);
getPosts() {
return this.http.get<Post[]>('https://jsonplaceholder.typicode.com/posts');
}
}import { Component, signal, computed, effect } from '@angular/core';
@Component({
selector: 'app-counter',
standalone: true,
template: `
<p>Count: {{ count() }} | Double: {{ double() }}</p>
<button (click)="increment()">+1</button>
`
})
export class CounterComponent {
count = signal(0);
double = computed(() => this.count() * 2);
constructor() {
effect(() => console.log('Count changed:', this.count()));
}
increment() { this.count.update(c => c + 1); }
}Count: 0 | Double: 0
| Command | Purpose |
|---|---|
ng new app-name | Create new project |
ng serve | Run dev server |
ng g c name | Generate component |
ng g s name | Generate service |
ng build | Production build (dist/ folder) |
ng test | Run unit tests |
ng update | Upgrade Angular version |
🎉 Congratulations! You've learned the core concepts of Angular.
If this tutorial helped you, share it and leave a comment below. — A143MK
Continue learning Angular with RxJS, route guards, HTTP interceptors, testing, performance, security and deployment.
Angular's HttpClient returns Observables. An Observable represents values that arrive over time. Use operators such as map to transform values and switchMap when a new search should replace an older request.
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError, of } from 'rxjs';
@Component({
selector: 'app-users',
standalone: true,
template: `
@if (error) {
<p>{{ error }}</p>
}
@for (user of (users$ | async) ?? []; track user.name) {
<p>{{ user.name }}</p>
}
`
})
export class UsersComponent {
private http = inject(HttpClient);
error = '';
users$ = this.http.get<{ name: string }[]>('/api/users').pipe(
catchError(() => {
this.error = 'Could not load users. Please try again.';
return of([]);
})
);
}async pipe in templates: Angular subscribes and cleans up for you.A guard can decide whether navigation is allowed. Return a redirect tree instead of navigating as a side effect. A resolver can load required data before a route is activated.
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const signedInGuard: CanActivateFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
return auth.isSignedIn()
? true
: router.createUrlTree(['/login']);
};{
path: 'account',
canActivate: [signedInGuard],
loadComponent: () => import('./account.component')
.then(m => m.AccountComponent)
}Functional interceptors are a central place to add common request behavior, such as attaching an access token. Clone requests because Angular HTTP requests are immutable.
import { inject } from '@angular/core';
import { HttpInterceptorFn } from '@angular/common/http';
import { AuthService } from './auth.service';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = inject(AuthService).accessToken();
if (!token) return next(req);
const authorized = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
return next(authorized);
};import { provideHttpClient, withInterceptors } from '@angular/common/http';
providers: [
provideHttpClient(withInterceptors([authInterceptor]))
]For simple shared state, a root-provided service with a private writable signal and a read-only public signal keeps updates controlled.
import { Injectable, computed, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class CartStore {
private itemsState = signal<string[]>([]);
items = this.itemsState.asReadonly();
itemCount = computed(() => this.itemsState().length);
add(item: string) {
this.itemsState.update(items => [...items, item]);
}
clear() {
this.itemsState.set([]);
}
}Use a dedicated state library when your app needs more complex workflows, data caching or debugging tools; choose the smallest approach that fits.
Tests help verify user-visible behavior. This example checks that a component renders its heading using Angular's test utilities.
import { TestBed } from '@angular/core/testing';
import { GreetingComponent } from './greeting.component';
describe('GreetingComponent', () => {
it('shows the greeting', async () => {
await TestBed.configureTestingModule({
imports: [GreetingComponent]
}).compileComponents();
const fixture = TestBed.createComponent(GreetingComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Hello');
});
});For HTTP services, use Angular's provideHttpClientTesting() and HttpTestingController to assert requests without calling a real API.
Load route code only when needed, and defer non-critical UI. These features can reduce the initial JavaScript users need to download.
{
path: 'reports',
loadComponent: () => import('./reports.component')
.then(m => m.ReportsComponent)
}@defer {
<app-analytics-chart />
} @placeholder {
<p>Chart will load when needed.</p>
} @loading (minimum 300ms) {
<p>Loading chart...</p>
}Also use pagination for large lists, track items in repeated views, and measure real performance before optimizing.
Before publishing, create and test a production build:
ng build
ng testDeploy the generated browser output to your hosting provider, configure the web server to serve the app entry point for client-side routes, and use HTTPS. Configure server-side credentials outside the frontend bundle.
🎉 You have completed Angular Tutorial Part 2. Keep building small features, test them, and consult the official Angular documentation as the framework evolves. — A143MK
Go further with dynamic forms, reusable components, signal and RxJS interop, server rendering, internationalization and scalable project structure.
Use a FormArray when the user can add or remove a variable number of controls. Keep validation in the form model so it can be tested and reused.
import { Component, inject } from '@angular/core';
import { FormArray, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-team-form',
standalone: true,
template: `
<form [formGroup]="form" (ngSubmit)="save()">
<div formArrayName="emails">
@for (control of emails.controls; track $index; let i = $index) {
<label [for]="'email-' + i">Email {{ i + 1 }}</label>
<input [id]="'email-' + i" [formControlName]="i" type="email">
<button type="button" (click)="removeEmail(i)">Remove</button>
}
</div>
<button type="button" (click)="addEmail()">Add email</button>
<button type="submit" [disabled]="form.invalid">Save</button>
</form>
`
})
export class TeamFormComponent {
private fb = inject(FormBuilder);
form = this.fb.group({
emails: this.fb.array([this.fb.control('', {
validators: [Validators.required, Validators.email]
})])
});
get emails() { return this.form.controls.emails; }
addEmail() {
this.emails.push(this.fb.control('', {
validators: [Validators.required, Validators.email]
}));
}
removeEmail(index: number) {
if (this.emails.length > 1) this.emails.removeAt(index);
}
save() {
if (this.form.valid) console.log(this.form.getRawValue());
}
}Content projection lets a reusable component provide layout and behavior while callers supply the content. Use a named slot when a component has distinct content areas.
<article class="card">
<header>
<ng-content select="[card-title]" />
</header>
<div class="card-body">
<ng-content />
</div>
<footer>
<ng-content select="[card-actions]" />
</footer>
</article><app-card>
<h2 card-title>Profile</h2>
<p>Update your contact details.</p>
<button card-actions type="button">Edit profile</button>
</app-card>Keep reusable components focused: expose clear inputs and outputs, and avoid coupling them directly to a specific page or API.
Implement ControlValueAccessor when a custom UI should work with formControlName. The Angular forms API calls these methods to keep the view and form model synchronized.
import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-rating',
standalone: true,
template: `
<label>
Rating
<input type="range" min="0" max="5"
[value]="value" [disabled]="disabled"
(input)="update($event)" (blur)="markTouched()">
</label>
<span>{{ value }} / 5</span>
`,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => RatingComponent),
multi: true
}]
})
export class RatingComponent implements ControlValueAccessor {
value = 0;
disabled = false;
private onChange = (value: number) => {};
private onTouched = () => {};
writeValue(value: number | null) { this.value = value ?? 0; }
registerOnChange(fn: (value: number) => void) { this.onChange = fn; }
registerOnTouched(fn: () => void) { this.onTouched = fn; }
setDisabledState(disabled: boolean) { this.disabled = disabled; }
update(event: Event) {
this.value = Number((event.target as HTMLInputElement).value);
this.onChange(this.value);
}
markTouched() { this.onTouched(); }
}Use toSignal to read an Observable as a signal in a component. Provide an initial value when the UI should have a useful state before the first result arrives.
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { HttpClient } from '@angular/common/http';
import { catchError, of } from 'rxjs';
interface Product {
id: number;
name: string;
}
@Component({
selector: 'app-products',
standalone: true,
template: `
<ul>
@for (product of products(); track product.id) {
<li>{{ product.name }}</li>
}
</ul>
`
})
export class ProductsComponent {
private http = inject(HttpClient);
products = toSignal(
this.http.get<Product[]>('/api/products').pipe(
catchError(() => of([]))
),
{ initialValue: [] }
);
}Choose one clear source of truth for each piece of state. Convert between signals and Observables at integration boundaries rather than repeatedly switching representations.
Server-side rendering (SSR) sends rendered HTML from the server. Hydration lets Angular take over that HTML in the browser, which can improve the first display and support content discovery.
ng add @angular/ssr.window and localStorage out of server-only execution paths.Design for translation early. Keep user-facing text out of business logic, allow translated labels to be longer, and format dates and numbers using locale-aware tools.
<h1 i18n="@@welcomeTitle">Welcome to the dashboard</h1>
<button i18n="@@saveButton">Save changes</button>const amount = new Intl.NumberFormat(locale, {
style: 'currency',
currency: 'USD'
}).format(total);Angular's extraction and build tools can prepare marked messages for translation. Verify each supported locale, including right-to-left layouts when applicable.
Group code around product features so each area can evolve independently. A small app does not need every possible abstraction; add boundaries when they make responsibilities clearer.
src/app/
core/
auth/
http/
shared/
ui/
pipes/
features/
products/
data-access/
pages/
ui/
products.routes.ts
orders/
data-access/
pages/
ui/
orders.routes.ts
app.routes.tsBuild a small product catalog to practice the concepts from Parts 1–3:
🎉 You have completed Angular Tutorial Part 3. Keep experimenting, testing and learning from real projects. — A143MK
Learn advanced dependency injection, RxJS workflow choices, resilient API handling, HTTP testing, and how to prepare an Angular feature for release.
Injection tokens let Angular provide values that are not classes, such as feature configuration. A provider on a component is scoped to that component and its descendants; a root provider is shared application-wide.
import { InjectionToken, inject } from '@angular/core';
export interface CatalogConfig {
apiUrl: string;
}
export const CATALOG_CONFIG =
new InjectionToken<CatalogConfig>('CATALOG_CONFIG');
export function injectCatalogConfig() {
return inject(CATALOG_CONFIG);
}{
path: 'catalog',
providers: [
{ provide: CATALOG_CONFIG, useValue: { apiUrl: '/api/catalog' } }
],
loadComponent: () => import('./catalog-page.component')
.then(m => m.CatalogPageComponent)
}Flattening operators define what happens when a new value arrives while earlier work is still running. Picking the right one prevents duplicate, stale or unexpectedly parallel requests.
| Operator | Use it when |
|---|---|
switchMap | Only the latest result matters, such as type-ahead search. |
concatMap | Every operation must run, in order, such as queued updates. |
mergeMap | Independent operations may run concurrently. |
exhaustMap | Ignore new triggers until the current operation finishes, such as blocking repeated submits. |
import { debounceTime, distinctUntilChanged, switchMap } from 'rxjs';
const results$ = searchControl.valueChanges.pipe(
debounceTime(250),
distinctUntilChanged(),
switchMap(query => catalogApi.search((query ?? '').trim()))
);Handle errors where the app can give useful feedback. Retrying a read request may be reasonable for transient network failures, but automatically retrying a create or payment request can duplicate a side effect.
import { HttpErrorResponse } from '@angular/common/http';
import { catchError, of, retry, throwError, timer } from 'rxjs';
readonly products$ = this.http.get<Product[]>('/api/products').pipe(
retry({
count: 2,
delay: (error: HttpErrorResponse, attempt) =>
error.status === 0 || error.status >= 500
? timer(attempt * 500)
: throwError(() => error)
}),
catchError(error => {
this.logger.error('Unable to load products', error);
this.loadError.set('Products could not be loaded. Try again.');
return of([]);
})
);Angular's HTTP testing utilities let a test inspect the outgoing request and provide a fake response without making a real network call.
import { TestBed } from '@angular/core/testing';
import {
provideHttpClient
} from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting
} from '@angular/common/http/testing';
import { CatalogApi } from './catalog.api';
describe('CatalogApi', () => {
let api: CatalogApi;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()]
});
api = TestBed.inject(CatalogApi);
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('loads products from the catalog endpoint', () => {
api.getProducts().subscribe(products => {
expect(products.length).toBe(1);
expect(products[0].name).toBe('Keyboard');
});
const request = http.expectOne('/api/products');
expect(request.request.method).toBe('GET');
request.flush([{ id: 1, name: 'Keyboard' }]);
});
});provideHttpClient() before provideHttpClientTesting() so the test provider replaces the real backend.Keep HTTP calls in a feature data service rather than scattering URLs through templates and components. Type the response shape and keep request methods explicit.
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface Product {
id: number;
name: string;
price: number;
}
export type NewProduct = Pick<Product, 'name' | 'price'>;
@Injectable({ providedIn: 'root' })
export class CatalogApi {
private http = inject(HttpClient);
private readonly url = '/api/products';
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(this.url);
}
createProduct(input: NewProduct): Observable<Product> {
return this.http.post<Product>(this.url, input);
}
}TypeScript types improve development feedback; they do not validate untrusted server responses at runtime. Validate critical data at the API boundary when the application requires it.
A production feature should communicate what is happening, not just render data after success. Plan for loading, empty, error and ready states, and prevent accidental duplicate submissions.
In a standalone component, import CurrencyPipe to use the currency formatting in this template.
@if (loading()) {
<p role="status">Loading products...</p>
} @else if (error()) {
<p role="alert">{{ error() }}</p>
<button type="button" (click)="reload()">Try again</button>
} @else if (products().length === 0) {
<p>No products yet. Add your first product.</p>
} @else {
<ul>
@for (product of products(); track product.id) {
<li>{{ product.name }} — {{ product.price | currency }}</li>
}
</ul>
}Use status and alert roles thoughtfully so assistive technologies announce updates without making the page noisy.
Run a consistent set of checks for every change. The exact test command can vary by Angular CLI version and project setup, so use the scripts already defined by your project.
npm ci
npm run lint
npm test -- --watch=false
npm run build -- --configuration production🎉 Parts 4 & 5 complete! You have practiced advanced Angular patterns and taken a feature from implementation through release. — A143MK
Review every part of the series, bring the concepts together in one final project, and celebrate finishing the tutorial.
Use these tiles to review the full learning path. Parts 4 and 5 are together in one post.
Angular basics, setup, components, templates, routing, forms, HTTP and Signals.
RxJS, route guards, interceptors, shared state, testing, performance and deployment.
Dynamic forms, reusable components, custom controls, SSR, i18n and architecture.
Dependency injection scopes, RxJS operator choices, API errors and HTTP testing.
Typed APIs, complete UI states, CI checks and production release preparation.
Bring the series together, check your skills and plan what to build next.
Build a small learning hub that lists courses, shows course details and lets a signed-in learner save favorites. Work through the project in small, testable steps:
Congratulations! You completed the Angular learning series. Keep building, keep testing, and enjoy creating with Angular.