Sunday, August 26, 2018

Angular custom directive for a input and output element




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

function declaration, expression and call/invoke/execution

  The  function  declaration defines a function with the specified parameters. The  function   keyword can be used to define a function ins...