guacamole
guacamole

Reputation: 325

Angular | How to set value of a signal based on the value of another signal?

I have two signals:

isFoo = this.store.selectSignal(abcd);  
isBar = signal(false);

isBar gets updated based on some other user interactions in the component. If the value of isFoo is true, isBar should always be false.

In the component's constructor, I am using an effect to handle that like so:

        effect(() => {
            if (this.Foo())
                this.isBar.set(false)
        },
        {allowSignalWrites: true})

Is there any other way to update the signal without having to use {allowSignalWrites: true} ? According to the documentation, that config option should be sparingly used. However, I am not sure how else to handle this scenario.

Upvotes: 3

Views: 4013

Answers (1)

Raphaël Balet
Raphaël Balet

Reputation: 8563

Use computed

If you wish to update a signal base on another one, you should use computed() instead

isFoo = this.store.selectSignal(abcd);  
isBar = computed(() => this.isFoo() ? false : true // or whatever logic

// For new users, this is the same ;)
isBar = computed(() => {
  if(this.isFoo()) return false
  else return true
}

Bonus : What is effect for?

For side effects, an example would be to be updating the url with some data.

Here an example

constructor(
  private _router: Router,
  private _activatedRoute: ActivatedRoute,
) {
  effect(() => {
    if (this.isFoo()) {
      const queryParams: Params = { foo: this.isFoo() ? 'foo' : 'bar' }

      this._router.navigate([], {
        relativeTo: this._activatedRoute,
        queryParams,
        queryParamsHandling: 'merge', // remove to replace all query params by provided
      })
    }
  })
}

Upvotes: 0

Related Questions