Angular Signals: Extending the Power of Angular
Angular Signals is a new feature that was introduced in Angular v16, released in May. It generated a lot of controversy in the community, as it extends the declarative way of coding around RxJs. In this article, we will explore what Angular Signals are and how they can be used.
Angular Signals is essentially a wrapper around a simple value that registers what depends on that value and notifies those dependents whenever its value changes. This feature is similar to the observer pattern, where an object maintains a list of its dependents and notifies them automatically of any state changes.
Despite its simple idea, Angular Signals has been scaring part of the community who feel this new feature could affect the declarative way (FRP) we code around RxJs. However, in the author's opinion, RxJs will still continue to be a protagonist in Angular development and that Angular Signals came only to help compose this ecosystem.
So, what are the possible uses for Angular Signals? The best way to validate the power of Angular Signals is to use it as much as possible. A good starting point is to base ourselves on the example provided in the RFC. Let's take a look at the code snippet below:
import { Signal } from '@angular/signals';
@Component({
selector: 'app-root',
template: `
<input [(ngModel)]="name">
<p>Hello, {{name}}!</p>
`
})
export class AppComponent {
name = '';
nameChanged = new Signal<string>();
constructor() {
this.nameChanged.subscribe((name: string) => {
console.log(`Name changed to ${name}`);
});
}
set name(value: string) {
this._name = value;
this.nameChanged.emit(value);
}
get name(): string {
return this._name;
}
}
In this example, we have an input field that is bound to the name
property of the component. Whenever the value of the input changes, the name
property is updated and the nameChanged
signal is emitted with the new value. The signal is subscribed to in the constructor of the component, and whenever the signal is emitted, the console logs the new value.
This is just a simple example, but it shows the potential of Angular Signals to simplify the code and make it more declarative. By using signals, we can avoid the need for complex event handling and callbacks, and instead rely on a simple and intuitive API.
In conclusion, Angular Signals is a powerful new feature that extends the power of Angular and simplifies the way we code around RxJs. While it may be controversial, it has the potential to make our code more declarative and easier to read. As developers, it is important to keep up with the latest news and features in the industry, and Angular Signals is definitely a feature worth exploring.