angularstate-managementangular-signalsangular18angular-state-managmement

How to Reset the Value of an Angular Signal to Its Default Value?


I'm working on an Angular application that utilizes the @angular/core signal feature. I have a signal that initially holds a default value, but its value changes based on user actions throughout the application. How can I reset this signal to its default value?

Additional Information: Angular version: v18


Solution

  • As far as I know there is no way to reset a signal back to an initial state, but we can declare the inital value in a property, then use the set method to reset the signal to it's initial value.

    import { Component, signal } from '@angular/core';
    import { bootstrapApplication } from '@angular/platform-browser';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      template: `
        <input [value]="input()" (input)="setInput($event)"/>
        <button (click)="resetToDefaults()">reset</button>
      `,
    })
    export class App {
      defaultInputVal = 'defaultValue';
      input = signal(this.defaultInputVal);
    
      setInput(event: any) {
        this.input.set(event?.target?.value);
      }
    
      resetToDefaults() {
        this.input.set(this.defaultInputVal);
      }
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo