Skip to content

Instantly share code, notes, and snippets.

@KEIII
Last active December 1, 2018 08:45
Show Gist options
  • Save KEIII/3e71c8e527f1a7890558f85f014a4043 to your computer and use it in GitHub Desktop.
Save KEIII/3e71c8e527f1a7890558f85f014a4043 to your computer and use it in GitHub Desktop.
rx-form-control.ts
import { FormControl } from '@angular/forms';
import { concat, of, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
type Nullable<T> = T | null;
/**
* @see AbstractControl.status
*/
export enum RxFormControlStatus {
VALID = 'VALID',
INVALID = 'INVALID',
PENDING = 'PENDING',
DISABLED = 'DISABLED',
}
export class RxFormControl<T = Nullable<string>> {
constructor(public readonly formControl: FormControl) {}
/**
* Shortcut.
* @see AbstractControl.valueChanges
*/
public readonly valueChanges$: Observable<Nullable<T>> = this.formControl.valueChanges;
/**
* The value of the control.
*/
public readonly value$: Observable<Nullable<T>> = concat(of(this.formControl.value), this.valueChanges$);
/**
* The validation status of the control.
*/
public readonly status$: Observable<RxFormControlStatus> = concat(of(this.formControl.status), this.formControl.statusChanges);
/**
* Is the control status invalid.
*/
public readonly invalid$: Observable<boolean> = this.status$.pipe(map(status => status === RxFormControlStatus.INVALID));
/**
* Shortcut.
* @see FormControl.setValue
*/
public setValue(value: Nullable<T>, options?: {
onlySelf?: boolean;
emitEvent?: boolean;
emitModelToViewChange?: boolean;
emitViewToModelChange?: boolean;
}) {
return this.formControl.setValue(value, options);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment