Get & Set Input Value Using Signals

Use Signals in Angular?

  1. Angular now recommends using Signals instead of normal properties.
  2. Signals provide:
  3. Better performance
  4. Faster DOM updates
  5. Cleaner and more reactive state management
  6. Using normal properties in interviews may indicate outdated Angular knowledge.


Goal of This Example

  1. Get value from an input field using Signals
  2. Display the value on the UI
  3. Update the value dynamically
  4. Reset the input value using a button
  5. Understand common mistakes
  6. Learn interview-important concepts


Template Code Explanation

Display Signal Value

<p>Value: {{ name() }}</p>
  1. Signals are accessed like functions.
  2. name() returns the current value of the signal.


Input Field (Get & Set Value)

<input
type="text"
[value]="name()"
(input)="setValue($event.target.value)"
>

Explanation:

  1. [value]="name()"
  2. → Binds the input field value with the signal.
  3. (input)
  4. → Triggers whenever the user types.
  5. $event.target.value
  6. → Gets the current input value.
  7. Calls setValue() function to update the signal.


Reset Button

<button (click)="resetValue()">Reset Value</button>
  1. Calls resetValue() method on click.
  2. Resets the signal to its default value.


Component Code Explanation

Import and Signal Declaration


user = signal("anil");
users = signal(['anil', 'sam', 'peter']);
  1. signal() creates a reactive state.
  2. Signals automatically update the UI when changed.


Updating a Signal

updateSignal() {
this.user.set("peter");
this.users.update((prevVal) => [...prevVal, 'bruce']);
}

Explanation:

  1. set() → Replaces the value
  2. update() → Updates the previous value
  3. Spread operator keeps old values and adds new ones


Set Input Value

setValue(val: string) {
this.name.set(val);
}
  1. Receives input value
  2. Updates the signal
  3. UI updates automatically


Reset Input Value

resetValue() {
this.name.set("Anil Sidhu");
}
  1. Resets signal value
  2. Input field and UI update instantly