I see that createSignal()
returns a SignalGetter<T>
, while signal()
returns a WritableSignal<T>
.
What are the key differences between these two in Angular, and in what scenarios would I use one over the other?
The createSignal()
is used internally when signal()
is defined. I do not think you will need createSignal()
since it seems to be an internal angular method and not even documented as a public API.
The code snippet is as below.
/**
* Create a `Signal` that can be set or updated directly.
*/
export function signal<T>(initialValue: T, options?: CreateSignalOptions<T>): WritableSignal<T> {
const signalFn = createSignal(initialValue) as SignalGetter<T> & WritableSignal<T>;
So the signal is a function that returns the value inside, which is created by createSignal
.
Then we also add the additional types using &
where it is a union of SignalGetter
(Signal reads) and WritableSignal
(Signal Writes).
Then we add the methods for updating the signal (WritableSignal
part of the signal).
signalFn.set = (newValue: T) => signalSetFn(node, newValue);
signalFn.update = (updateFn: (value: T) => T) => signalUpdateFn(node, updateFn);
signalFn.asReadonly = signalAsReadonlyFn.bind(signalFn as any) as () => Signal<T>;
if (ngDevMode) {
signalFn.toString = () => `[Signal: ${signalFn()}]`;
node.debugName = options?.debugName;
}
return signalFn as WritableSignal<T>;