Angular question detail
Explain Angular Signals with an example.
In this example, we create a signal named count and initialize it with a value of 0. We then connect to the signal, allowing us to be notified whenever its value changes. Finally, we add a button that increments the count when clicked.
When the button is clicked, the incrementCount() method is called. This method sets the new value of the count signal to 1. Objects connected to the signal (subscribers) are then notified of the change, and the updated value is displayed in the UI.
In TypeScript file
import { Component, OnInit } from '@angular/core';
import { signal, computed } from '@angular/core'; // Import from '@angular/core'
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
count = signal(0);
doubleCount = computed(() => this.count() * 2);
constructor() {}
ngOnInit() {
// Optional logging for debugging displayedCount changes
// console.log('Displayed count changed to:', this.displayedCount());
}
incrementCount() {
this.count.set(this.count() + 1);
}
decrementCount() {
this.count.update((value) => Math.max(0, value - 1));
}
}
In HTML file
<h1>Angular Signals Example</h1>
<button (click)="incrementCount()" style="margin-right: 10px;">Increment Count</button>
<button (click)="decrementCount()">Decrement Count</button>