👋 Let’s learn signal in Angular
Signal =Value + Change notification
A signal is just a special type of variable that holds a value.
But unlike other variables, a signal also provides notification when the variable value changes.
A signal always has a initial value.
Benefits of signal: It helps to reduce change detection cycle numbers so performance improvements.
Signal can be used in
- component communications
- State management
Just a example of signal type variable:
// Normal variable:
let x=5;
console.log(x)
// Signal variable:
let x = signal(5);
console.log(x());
Signals is of two types:
- Writable Signals ( Set and Update)
- Computed Signals ( Computed )
Reading signals in OnPush components.
Effect is an operation that runs whenever one or more signal value changes.
Here I will show you example of using signal.
Writable signal:
count= signal(2);
ngOnInit(): void {
console.log("start", this.count());
this.count.set(3);
console.log("after set signal", this.count());
this.count.update((data:number)=>{
return data*2;
})
console.log("after update signal", this.count());
}
Computed Signal:
Computed signals are read only signals that derives their value from other signals. This signals are defined using computed function.
number1= signal(3);
number2= signal(4);
computedCount= computed(()=> this.number1()+ this.number2())
ngOnInit(): void {
console.log("computed signal",this.computedCount())
}
whenever number1 or number2 updates, computed property gets update.
Effect:
Effect is specially is useful for OnPush type component:
Effect runs whenever one or more signal value change. Using effect function we can create an effect.
Effect always run at least once and always execute asynchronously during the change detection process. Whenever any of the signal value change, the effect runs again.
constructor() {
effect(()=>{
console.log("effect signal- Last updated value",this.count())
})
}
I will be posting some mini application example upcoming days.
Stay tuned for upcoming latest angular article, Happy Learning !!