Get & Set Input Value Using Signals
Use Signals in Angular?
- Angular now recommends using Signals instead of normal properties.
- Signals provide:
- Better performance
- Faster DOM updates
- Cleaner and more reactive state management
- Using normal properties in interviews may indicate outdated Angular knowledge.
Goal of This Example
- Get value from an input field using Signals
- Display the value on the UI
- Update the value dynamically
- Reset the input value using a button
- Understand common mistakes
- Learn interview-important concepts
Template Code Explanation
Display Signal Value
<p>Value: {{ name() }}</p>
- Signals are accessed like functions.
name()returns the current value of the signal.
Input Field (Get & Set Value)
<input
type="text"
[value]="name()"
(input)="setValue($event.target.value)"
>
Explanation:
[value]="name()"- → Binds the input field value with the signal.
(input)- → Triggers whenever the user types.
$event.target.value- → Gets the current input value.
- Calls
setValue()function to update the signal.
Reset Button
<button (click)="resetValue()">Reset Value</button>
- Calls
resetValue()method on click. - Resets the signal to its default value.
Component Code Explanation
Import and Signal Declaration
user = signal("anil");
users = signal(['anil', 'sam', 'peter']);
signal()creates a reactive state.- Signals automatically update the UI when changed.
Updating a Signal
updateSignal() {
this.user.set("peter");
this.users.update((prevVal) => [...prevVal, 'bruce']);
}
Explanation:
set()→ Replaces the valueupdate()→ Updates the previous value- Spread operator keeps old values and adds new ones
Set Input Value
setValue(val: string) {
this.name.set(val);
}
- Receives input value
- Updates the signal
- UI updates automatically
Reset Input Value
resetValue() {
this.name.set("Anil Sidhu");
}
- Resets signal value
- Input field and UI update instantly