Last active
December 1, 2018 08:45
-
-
Save KEIII/3e71c8e527f1a7890558f85f014a4043 to your computer and use it in GitHub Desktop.
rx-form-control.ts
This file contains 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 { 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