Tuesday, March 11, 2025

#9 Signals

 

Understanding Angular 19 Signals

In Angular 19, signals are a reactivity model introduced to improve performance, simplify state management, and provide fine-grained change detection without relying on RxJS. Signals help track state changes efficiently and work seamlessly with Angular’s rendering system.

Key Features of Signals

  1. Declarative State Management - Makes state tracking more predictable.
  2. Automatic Dependency Tracking - Updates components when signal values change.
  3. Optimized Rendering - Reduces unnecessary component re-renders.
  4. Better Performance - No need for manual ChangeDetectionStrategy.OnPush.

Step-by-Step Angular 19 Signals Example

We will create a basic Angular 19 application where we use signals to manage a counter.


Step 1: Create a New Angular 19 Project

Ensure you have Angular CLI 19 installed. If not, update it:

npm install -g @angular/cli@latest

Now, create a new Angular project:

ng new angular-signals-demo
cd angular-signals-demo

Select SCSS or any other styling option based on your preference.


Step 2: Install Required Dependencies

Angular Signals are built-in, so you don’t need additional packages.

Just ensure your project is running:

ng serve

Step 3: Create a Counter Service using Signals

Generate a service to manage our counter state using signals.

ng generate service services/counter

Now, modify counter.service.ts:

import { Injectable, signal } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class CounterService {
  // Define a signal with an initial value of 0
  count = signal(0);

  // Method to increment the count
  increment() {
    this.count.set(this.count() + 1);
  }

  // Method to decrement the count
  decrement() {
    this.count.set(this.count() - 1);
  }

  // Method to reset the count
  reset() {
    this.count.set(0);
  }
}

Step 4: Use Signals in a Component

Generate a new component to display and update the counter.

ng generate component components/counter

Now, update counter.component.ts:

import { Component } from '@angular/core';
import { CounterService } from 'src/app/services/counter.service';

@Component({
  selector: 'app-counter',
  templateUrl: './counter.component.html',
  styleUrls: ['./counter.component.scss'],
})
export class CounterComponent {
  constructor(public counterService: CounterService) {}

  // Methods to modify the count
  increment() {
    this.counterService.increment();
  }

  decrement() {
    this.counterService.decrement();
  }

  reset() {
    this.counterService.reset();
  }
}

Step 5: Update the Counter Component HTML

Modify counter.component.html:

<div class="counter-container">
  <h2>Counter with Angular 19 Signals</h2>
  <p>Current Count: {{ counterService.count() }}</p>

  <button (click)="increment()">+</button>
  <button (click)="decrement()">-</button>
  <button (click)="reset()">Reset</button>
</div>

Step 6: Add Counter Component to App Component

Modify app.component.html to include the counter:

<h1>Welcome to Angular 19 Signals Demo</h1>
<app-counter></app-counter>

Step 7: Style the Counter (Optional)

Modify counter.component.scss:

.counter-container {
  text-align: center;
  margin-top: 20px;

  h2 {
    font-size: 1.5rem;
    margin-bottom: 10px;
  }

  p {
    font-size: 1.2rem;
    font-weight: bold;
  }

  button {
    font-size: 1rem;
    margin: 5px;
    padding: 10px 15px;
    cursor: pointer;
    border: none;
    background-color: #007bff;
    color: white;
    border-radius: 5px;
  }

  button:hover {
    background-color: #0056b3;
  }

  button:nth-child(2) {
    background-color: #dc3545;
  }

  button:nth-child(2):hover {
    background-color: #c82333;
  }

  button:nth-child(3) {
    background-color: #6c757d;
  }

  button:nth-child(3):hover {
    background-color: #5a6268;
  }
}

Step 8: Run the Project

Start the Angular application:

ng serve

Open the browser at http://localhost:4200 and see your signal-powered counter in action!


Key Takeaways

  • signal(value) creates a reactive state variable.
  • .set(newValue) updates the signal’s value.
  • .update(fn) modifies the value based on the current state.
  • Signals are synchronous and automatically notify the UI of changes.

This example demonstrates how easy it is to use signals in Angular 19 for state management. Would you like to extend this with more features like async operations or effects? 🚀


Another Simple Hands-on about Signal:

Step 1: ng new ang19-signals

            cd ang19-signals

            code .

            in terminal : npm i browser

Step 2:

Modify main.ts as below:

import {Component, signal, computed} from '@angular/core';
import {bootstrapApplication} from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  template: `
    <h1> ImmBizSoft inTern Training -Concept of Angular Signals</h1>
    <hr color="red">
    <h2>Cookie Recipe</h2>
    <hr color="blue">

    <label>
      # of cookies:
      <input type="range" min="5" max="100" step="5" [value]="count()" (input)="update($event)" />
      {{ count() }}
    </label>

    <p>Butter: {{ butter() }} cup(s)</p>
    <p>Sugar&nbsp;: {{ sugar() }} cup(s)</p>
    <p>Flour&nbsp;: {{ flour() }} cup(s)</p>
    <p>Copyright &copy; 2025 R-M-C WebSite . All rights reserved.</p>.
  `,
})
export class CookieRecipe {
  count = signal(5);

  butter = computed(() => this.count() * 0.1);
  sugar = computed(() => this.count() * 0.05);
  flour = computed(() => this.count() * 0.2);

  update(event: Event) {
    const input = event.target as HTMLInputElement;
    this.count.set(parseInt(input.value));
  }
}

bootstrapApplication(CookieRecipe);


ng serve 


No comments:

Post a Comment

#11 @Output

  Understanding @Output() in Angular 19 The @Output() decorator in Angular 19 is used to send data from a child component to a parent co...