Skip to content

Instantly share code, notes, and snippets.

@e-oz
Created February 12, 2025 09:57
Show Gist options
  • Save e-oz/4e0a26599edd8747dc3f35d5e8f8e90e to your computer and use it in GitHub Desktop.
Save e-oz/4e0a26599edd8747dc3f35d5e8f8e90e to your computer and use it in GitHub Desktop.
Function to get control/form value as a signal
import { computed, type Injector, isSignal, signal, type Signal, untracked } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { AbstractControl } from '@angular/forms';
import { startWith } from 'rxjs';
/**
* Returns a signal that contains the value of a control (or a form).
* @param control
* @param injector
*/
export function getControlValueSignal<T>(control: AbstractControl<T> | Signal<AbstractControl<T> | undefined>, injector: Injector): Signal<T | undefined> {
const valueChanges = computed(() => {
const ctrl = isSignal(control) ? control() : control;
if (!ctrl) {
return signal(undefined);
}
return untracked(() => toSignal(
ctrl.valueChanges.pipe(startWith(ctrl.value)),
{
injector,
initialValue: undefined,
},
));
});
return computed(() => valueChanges()());
}
@RaimonxDev
Copy link

Nice, Thanks for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment