Reputation: 325
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
Reputation: 8563
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
}
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