0

i create this directive for find when the value of input was changed to somthing .

import { Directive, HostListener } from '@angular/core';

@Directive({
  selector: '[ktCloseDatePciker]'
})
export class CloseDatePcikerDirective {


  constructor() { }
  @HostListener('change', ['$event'])
  click(event) {
    console.log('clicked!');
  }

}

and use that in the html by this :

                <input #dateDirectivePicker="dpDayPicker" ktCloseDatePciker (change)="close()" formControlName="Publish_CalendarDate" id="date-lrt" theme="dp-material" matInput mode="daytime" [dpDayPicker]="datePickerConfigStart" />

but it not worked , when i change the value it can not write console in driective.

whats the problem ? how can solve this problem ?

kianoush dortaj
  • 81
  • 1
  • 1
  • 6

2 Answers2

0

Change the event's name from 'change' to 'input', example:

directive
import { Directive, HostListener } from "@angular/core";

@Directive({
  selector: "[ktCloseDatePciker]"
})
export class CloseDatePcikerDirective {
  constructor() {}
  @HostListener("input", ["$event"])
  input(event) {
    console.log("typed!" + event.target.value);
  }
}
template
<input ktCloseDatePciker (change)="close()"/>

The 'change' event is triggered when the input loses focus, which is how it was intended to be used (ref):

MDN input event:

Note: The input event is fired every time the value of the element changes. This is unlike the change event, which only fires when the value is committed, such as by pressing the enter key, selecting a value from a list of options, and the like.

Community
  • 1
  • 1
shrys
  • 5,860
  • 2
  • 21
  • 36
  • i can not type any thing on that . i have datepicker on that input , when i select the date it set value on the input but not write any things in console – kianoush dortaj Mar 07 '20 at 13:56
  • @kianoushdortaj please check this [link](https://stackblitz.com/edit/angular-eyc6gs?file=src%2Fapp%2Fclose-date-pciker.directive.ts), i tried reproducing your issue – shrys Mar 07 '20 at 14:08
0

You need to use onChange event instead of change to get picker changes. and need to use close event for when the picker closed.

for changes :

 <input #dateDirectivePicker="dpDayPicker" ktCloseDatePciker (onChange)="close()" formControlName="Publish_CalendarDate" id="date-lrt" theme="dp-material" matInput mode="daytime" [dpDayPicker]="datePickerConfigStart" />

when closed picker :

<input #dateDirectivePicker="dpDayPicker" ktCloseDatePciker (close)="close()" formControlName="Publish_CalendarDate" id="date-lrt" theme="dp-material" matInput mode="daytime" [dpDayPicker]="datePickerConfigStart" />