Angular Signals – Basic Tutorial with Small Examples
Angular Signals are used to manage data and automatically update the UI whenever the data changes.
1. signal()
Creates a writable signal.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-root',
standalone: true,
template: `
<h2>{{ count() }}</h2>
`
})
export class AppComponent {
count = signal(10);
}Output: 10
2. set()
Used to assign a new value.
count = signal(10);
changeValue() {
this.count.set(20);
}3. update()
Used to update the existing value.
count = signal(10);
increment() {
this.count.update(value => value + 1);
}4. Counter Example
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-root',
standalone: true,
template: `
<h2>Count: {{ count() }}</h2>
<button (click)="increment()">+</button>
<button (click)="decrement()">-</button>
<button (click)="reset()">Reset</button>
`
})
export class AppComponent {
count = signal(0);
increment() {
this.count.update(v => v + 1);
}
decrement() {
this.count.update(v => v - 1);
}
reset() {
this.count.set(0);
}
}5. computed()
Used to calculate a value based on other signals.
import { Component, signal, computed } from '@angular/core';
@Component({
selector: 'app-root',
standalone: true,
template: `
<h2>Price: {{ price() }}</h2>
<h2>Quantity: {{ quantity() }}</h2>
<h2>Total: {{ total() }}</h2>
`
})
export class AppComponent {
price = signal(100);
quantity = signal(2);
total = computed(() =>
this.price() * this.quantity()
);
}Output: Total = 200
6. effect()
Executes code whenever its dependent signals change.
import { Component, signal, effect } from '@angular/core';
@Component({
selector: 'app-root',
standalone: true,
template: `
<h2>{{ count() }}</h2>
<button (click)="count.update(v => v + 1)">
Increment
</button>
`
})
export class AppComponent {
count = signal(0);
constructor() {
effect(() => {
console.log('Count:', this.count());
});
}
}7. Signal with String
name = signal('Shiva');
changeName() {
this.name.set('Rahul');
}HTML:
<h2>{{ name() }}</h2>
<button (click)="changeName()">Change Name</button>8. Signal with Array
students = signal(['Rahul', 'Amit', 'Priya']);
addStudent() {
this.students.update(list => [...list, 'Vijay']);
}HTML:
@for (student of students(); track student) {
<p>{{ student }}</p>
}
<button (click)="addStudent()">Add Student</button>9. Signal with Object
user = signal({
name: 'Shiva',
age: 41
});
updateAge() {
this.user.update(u => ({
...u,
age: u.age + 1
}));
}HTML:
<h2>{{ user().name }}</h2>
<h2>{{ user().age }}</h2>
<button (click)="updateAge()">Update Age</button>10. Important Signal Functions
Function | Purpose |
|---|---|
| Create a writable signal |
| Assign a new value |
| Update an existing value |
| Calculate derived values |
| Execute side effects |
| Create a read-only signal view |
| Create a writable linked signal |
Remember these three concepts first:
signal()– Store data.computed()– Calculate data.effect()– Perform side effects.
Angular Route Guards – Basic Tutorial with Small Examples
Angular Route Guards are used to control navigation between routes based on certain conditions.
For example:
Only logged-in users can access the Dashboard.
Only Admin users can access the Admin page.
Prevent users from leaving a form with unsaved changes.
1. Types of Route Guards in Angular
Angular provides five main route guard types.
Guard | Purpose |
|---|---|
| Controls access to a route |
| Controls access to child routes |
| Controls leaving a route |
| Controls whether a route can match |
| Legacy guard for lazy-loaded modules (deprecated) |
For modern Angular, use functional guards.
2. CanActivate Guard
Example: Only logged-in users can access the Dashboard.
Step 1: Create an authentication service.
auth.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AuthService {
isLoggedIn = false;
}Step 2: Create an authentication guard.
auth.guard.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = () => {
const auth = inject(AuthService);
const router = inject(Router);
if (auth.isLoggedIn) {
return true;
}
return router.createUrlTree(['/login']);
};Step 3: Apply the guard in routes.
app.routes.ts
import { Routes } from '@angular/router';
import { authGuard } from './auth.guard';
export const routes: Routes = [
{
path: 'login',
loadComponent: () =>
import('./login.component')
.then(m => m.LoginComponent)
},
{
path: 'dashboard',
canActivate: [authGuard],
loadComponent: () =>
import('./dashboard.component')
.then(m => m.DashboardComponent)
}
];Explanation:
If
isLoggedInis true, the Dashboard opens.If
isLoggedInis false, the user redirects to Login.
3. CanActivateChild Guard
Used to protect all child routes of a parent route.
import { CanActivateChildFn } from '@angular/router';
export const childGuard: CanActivateChildFn = () => {
console.log('Child route accessed');
return true;
};Apply it:
{
path: 'admin',
canActivateChild: [childGuard],
children: [
{
path: 'users',
component: UsersComponent
},
{
path: 'reports',
component: ReportsComponent
}
]
}Both Users and Reports routes are protected.
4. CanDeactivate Guard
Used to prevent users from leaving a page.
Example: A user is filling out a form but has not saved the data.
import { CanDeactivateFn } from '@angular/router';
export interface CanLeave {
canLeave: () => boolean;
}
export const deactivateGuard: CanDeactivateFn<CanLeave> =
(component) => {
return component.canLeave();
};Component:
export class EditComponent implements CanLeave {
canLeave() {
return confirm('Are you sure you want to leave?');
}
}Route configuration:
{
path: 'edit',
component: EditComponent,
canDeactivate: [deactivateGuard]
}5. CanMatch Guard
Used to decide whether Angular should match a particular route.
import { CanMatchFn } from '@angular/router';
export const adminGuard: CanMatchFn = () => {
return true;
};Route:
{
path: 'admin',
canMatch: [adminGuard],
component: AdminComponent
}If the guard returns false, Angular tries other matching routes instead of activating this route.
6. Functional Guard vs Class-Based Guard
Functional Guard | Class-Based Guard |
|---|---|
Modern approach | Older approach |
Uses functions | Uses classes |
Uses | Uses constructor injection |
Recommended for new applications | Legacy approach |
0 Comments
POST Answer of Questions and ASK to Doubt