Skip to content

Instantly share code, notes, and snippets.

@merlosy
Last active January 23, 2018 09:13
Show Gist options
  • Save merlosy/461a2259cc32481847212e95a0c4cb35 to your computer and use it in GitHub Desktop.
Save merlosy/461a2259cc32481847212e95a0c4cb35 to your computer and use it in GitHub Desktop.
Angular Material NullabelRadioButton
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment