ref:
https://stackblitz.com/edit/reset-spy-directive?file=app%2Freset-spy.directive.ts
https://stackoverflow.com/questions/49532872/angular-2-custom-directive-for-a-input-element-how-to-detect-a-reset-call
import { Directive, Output, EventEmitter } from '@angular/core';
import { NgControl } from '@angular/forms';
import { Subscription } from 'rxjs/Subscription';
import {map, pairwise, startWith, filter} from 'rxjs/operators';
@Directive({
selector: '[resetSpy]',
})
export class ResetSpyDirective {
@Output() reset = new EventEmitter<void>();
subscription: Subscription;
constructor(private ngControl: NgControl) { }
ngOnInit() {
const reset$ = this.ngControl.control.valueChanges.pipe(
map(v => this.ngControl.pristine),
startWith(this.ngControl.pristine),
pairwise(),
filter(([from, to]) => !from && to)
);
this.subscription = reset$.subscribe(() => this.reset.emit());
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
No comments:
Post a Comment