Kobi Hari
Kobi Hari

Reputation: 1258

How to update signal based on input signal in Angular 17.1

I have an angular service that is implemented using signals.

    export class MyService {
        private idSignal = signal(0);
        setId(id: number) { 
            this.idSignal.set(id);
        }
    }

I have a component that injects this service. The component has a required input called id:

    export class MyComponent {
       private service = inject(MyService);
       id = input.required<number>();
    }

I would like to set the id on the service according to the value of the id input in the component. One option I considered was to use an effect, but it is not recommended to set the value of signals inside effects. How would I do it without breaking best practices, and potentially cause circular dependencies.

Upvotes: 2

Views: 1508

Answers (1)

Jim Schmit
Jim Schmit

Reputation: 14

You can use the untracked() (https://angular.io/api/core/untracked) function inside the effect(). All signal mutations withing untracked will not trigger other effects using the mutated signal.

constructor(){
 effect(() => 
 {
    untracked(() => // do your mutation);
 }
);
}

The only problem I see is that for now I don't know how to update an InputSignal...

Upvotes: -1

Related Questions