最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

state management - How to Reset the Value of an Angular Signal to Its Default Value? - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question asked Nov 18, 2024 at 10:08 Hansana PrabathHansana Prabath 1512 silver badges13 bronze badges 3
  • 1 This is currently not supported by Angular Signals, but sounds like a reasonable feature to have. You can create an issue in their issue tracker: github/angular/angular/issues – JSON Derulo Commented Nov 18, 2024 at 10:11
  • I'd go with Naren solution, having signal keep their initial value would increase their memory footprint. – Matthieu Riegler Commented Nov 18, 2024 at 10:24
  • I’ve created an issue regarding this. please consider upvoting the issue to help bring attention to it. here is the link: github/angular/angular/issues/58715 – Hansana Prabath Commented Nov 18, 2024 at 10:24
Add a comment  | 

1 Answer 1

Reset to default 2

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

发布评论

评论列表(0)

  1. 暂无评论