useFormValue
Returns the current value of a FormGroup as a signal. The signal updates reactively whenever the form value changes.
Usage
typescript
import { useFormValue } from 'ng-reactive-utils';
@Component({
template: `
<form [formGroup]="form">
<input formControlName="firstName" />
<input formControlName="lastName" />
</form>
<p>Hello, {{ formValue().firstName }} {{ formValue().lastName }}!</p>
<pre>{{ formValue() | json }}</pre>
`,
})
class GreetingComponent {
form = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
});
formValue = useFormValue<{ firstName: string; lastName: string }>(this.form);
// Use in computed signals
fullName = computed(() => `${this.formValue().firstName} ${this.formValue().lastName}`.trim());
}Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
form | FormGroup | required | The FormGroup to get the value from |
Returns
Signal<T> - A readonly signal containing the current form value
Notes
- Uses
toSignalwithform.valueChangesobservable - Type parameter
Tshould match your form's value structure - Updates reactively on every value change (patchValue, setValue, reset)
- Can be used in computed signals for derived state
Source
ts
import { Signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { FormGroup } from '@angular/forms';
/**
* Returns the current value of a FormGroup as a signal.
* The signal updates reactively whenever the form value changes.
*
* @param form - The FormGroup to get the value from
* @returns A signal containing the current form value
*
* @example
* ```typescript
* @Component({
* template: `
* <form [formGroup]="form">
* <input formControlName="email" />
* </form>
* <pre>{{ formValue() | json }}</pre>
* `
* })
* class MyComponent {
* form = new FormGroup({
* email: new FormControl('')
* });
* formValue = useFormValue<{ email: string }>(this.form);
* }
* ```
*/
export const useFormValue = <T extends object>(form: FormGroup): Signal<T> => {
return toSignal(form.valueChanges, {
initialValue: form.value,
}) as Signal<T>;
};