Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading