-
Notifications
You must be signed in to change notification settings - Fork 25.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add WritableComputed to allow computed with write operations #55673
Comments
|
Did you also consider splitting up your computation and writing logic? Something like the following: class Test {
value = input.required<string>();
writableValue = signal<string | undefined>(undefined);
computedValue = computed(() => this.writableValue() ?? this.value() + 1);
}IMHO Angular shouldn't offer a signal which is both computed and writable. It leads to ambiguity, you will never know whether the current value of the signal comes from the computation or from a signal write. Also when the input is updated, the previously set value will be reset, which I assume would be an unintended side effect. |
This won't reset neither |
class Test {
value = input.required<string>();
// the trick: project the input's value to a `WritableSignal` of that value.
// when the input changes, the inner `WritableSignal` will be replaced with a new one.
writableInnerValue = computed(() => signal(this.value()));
// helper to get rid of the double read
innerValue = () => this.writableInnerValue()();
setInnerValue(value: string): void {
// the WritableSignal allows for internal mutation
this.writableInnerValue().set(value);
}
} |
|
Or pulled out into a helper function: interface MirrorSignal<T> {
(): T;
set(value: T);
}
function mirror<T>(outer: Signal<T>): MirrorSignal<T> {
const inner = computed(() => signal(outer()));
const mirror: MirrorSignal<T> = () = inner()();
mirror.set = (value: T) => untracked(inner).set(value);
return mirror;
} |
|
Hey! Well, I assume the most updated answer to this issue would be something like: once this PR is merged, just use
So the code would be something like: class Test {
value = input.required<string>();
tempValue = signal('');
valueWatcher = effect(() => this.tempValue.set(this.value())); // tempValue defined in onInit
// ...
}Assuming what I wrote is more or less correct, I still have the feeling we might miss something... as soon as (for example) the input(s) gets more complicated. Here is a basic example: @Component({
template: `
// User (potential complex object)
<div>user: {{ user() | json }}</div>
<input type="text" [ngModel]="name()" (ngModelChange)="changeName($event)"/>
<div>{{ name() }}</div>
<input type="text" [(ngModel)]="signalName"/>
<div>{{ signalName() }}</div>
`,
})
export class ViewEditUser {
user = signal<{ name: string }>({ name: 'John' }); // consider it readOnly
name = mirror(() => this.user().name); // helper func above
changeName(name: string) {...}
signalName = signal('');
signalNameWatcher = effect(() => this.signalName.set(this.user().name); // already adapted
// ...
}https://stackblitz.com/edit/stackblitz-starters-bw7fmd?file=src%2Fmain.ts Just to make things easier, I'm using a simple In such cases, I'd basically like to define a writable signal that gets updated any time
Just for clarity: this is not a big problem... it's mostly adding some practical reasons in favour of considering As usual thanks a lot! |
Probably this will copied over to ngxtension 😅 edit: added PR |
|
I guess you can support interface MirrorSignal<T> {
(): T;
set(value: T): void;
update(updateFn: (value: T) => T): void;
// asReadonly(): Signal<T>; ??? once you call it, you get one signal(expression())
}
function mirror<T>(expression: () => T): MirrorSignal<T> {
const inner = computed(() => signal(expression()));
const mirror: MirrorSignal<T> = () => inner()();
mirror.set = (value: T) => {
const newS = untracked(inner);
return newS.set(value);
};
mirror.update = (updateFn: (value: T) => T) => {
const newS = untracked(inner);
return newS.update(updateFn);
};
return mirror;
}But don't think there's a way for And not totally sure My 2 cents! |
|
Update for anyone tracking this issue - we do see number of use-cases (similar to the originally exposed one) and thinking of adding a new utility / primitive. The exact naming TBD (currently hesitating between Conceptually it is a signal (with all the signal methods: set, update, asReadonly) that has its state initialized and reset based on some other reactive state (computed). |
|
Thanks a lot for the great news! Seems like in svelte they called it Strictly personal: regarding the name, I like So, something like:
I'd stay away from Just my 2 (not requested) cents! 😅 |
|
Oops PR reverted (apologise for the spamming then)... 😅 The follow up discussion is anyway interesting! |


Which @angular/* package(s) are relevant/related to the feature request?
core
Description
Revival with use case of #50498
Currently
signalproduces a writable signal.Currently
computedproduces a non writable signal.What I am missing is a
writableComputed.Use case example:
I have a required input called
valuebut inside the component I can edit this value without affecting the outside. At the end an apply button is clicked and I emit the new value via an output.Something like this:
The first problem is
tempValueisn't based onvalue.The second problem is when
valueis changed from outside. At this point I wish to discardtempValueand start fresh with the newvalue.If I had
writableComputedI could do:Which means anytime
valuechanges it becomes the newtempValuevalue. IftempValueis edited the new edit is thetempValuenew value until something gets changed invalue.Proposed solution
A new
writableComputedwhich tracks the value inside based on the writeable part and will get reset each time the computed function runs to what it creates.Examples:
Alternatives considered
Using effect. The downside is with required inputs.
This will result in
tempValuehavingundefinedinitially and for example inngOnInitit will still haveundefinedalthoughvaluealready have the actual value set. Also a computed will have its value set too.using
writableComputedinngOnInitwill have the correct computed value.Another option is that scenario hints that something I am doing is wrong from the basis and I would like to hear better suggestions how to handle it.
The text was updated successfully, but these errors were encountered: