Created
February 12, 2025 09:57
-
-
Save e-oz/4e0a26599edd8747dc3f35d5e8f8e90e to your computer and use it in GitHub Desktop.
Function to get control/form value as a signal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, Thanks for sharing