|
import { Directive, HostListener, OnInit, OnDestroy } from '@angular/core'; |
|
import { NgControl } from '@angular/forms'; |
|
import { combineLatest, tap, filter, take, startWith, debounceTime } from 'rxjs/operators'; |
|
import { of } from 'rxjs/observable/of'; |
|
import { BehaviorSubject } from 'rxjs/BehaviorSubject'; |
|
|
|
@Directive({ |
|
selector: '[appNullableRadioButton]' |
|
}) |
|
export class NullableRadioButtonDirective implements OnInit, OnDestroy { |
|
|
|
private _previousValue: boolean | null = null; |
|
private _subject: BehaviorSubject<any[]>; |
|
|
|
@HostListener('click') async onClick() { |
|
const newval = await this.control.valueChanges.pipe( |
|
startWith(this.control.value), |
|
debounceTime(250), |
|
take(1) |
|
).toPromise(); |
|
// console.log(newval, this._previousValue); |
|
if (!this.control.disabled) { |
|
this._subject.next([newval, this._previousValue]); |
|
} |
|
} |
|
|
|
constructor(private control: NgControl) { } |
|
|
|
ngOnInit(): void { |
|
this._subject = new BehaviorSubject([this.control.value, undefined]); |
|
this._previousValue = this.control.value; |
|
|
|
this._subject.pipe( |
|
tap((v: any[]) => { |
|
this._previousValue = v[0]; |
|
}), |
|
filter(values => values[0] === values[1]), |
|
tap(() => { |
|
this.control.control.setValue(null); |
|
this._previousValue = null; |
|
}) |
|
).subscribe(); |
|
|
|
} |
|
|
|
ngOnDestroy(): void { |
|
this._subject.complete(); |
|
this._subject.unsubscribe(); |
|
} |
|
|
|
} |