Idir Ouhab Meskine
Idir Ouhab Meskine

Reputation: 587

Change event with jQuery datepicker and Angular 2

I have some problems to catch the change event when I use the jQuery datepicker plugin and I'm trying to use the (change) method to catch the change but seems that when I'm using this plugin, angular can't catch it.

@Component({
    selector: 'foo-element',
    template: '<input type="text" (change)="checkDates($event)" id="foo_date_picker" class="datepicker">'
})

export class FooComponentClass implements AfterViewInit {

    ngAfterViewInit():any{
        $('#end_day').datepicker();
    }

    private function checkDates(e){
        console.log("Please, catch the change event ): ");
    }
}

I have removed the datepicker initialization and works fine, but when I use it again... don't works.

Someone can help me!

Thanks so much.

Upvotes: 2

Views: 1856

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202176

You could implement the following directive:

@Directive({
  selector: '[datepicker]'
})
export class DatepickerDirective {
  @Output()
  change:EventEmitter<string> = new EventEmitter();

  constructor(private elementRef:ElementRef) {
  }

  ngOnInit() {
    $(this.elementRef.nativeElement).datepicker({
      onSelect: (dateText) => {
        this.change.emit(dateText);
      }
    });
  }
}

This way you will be able to catch a change event like this:

@Component({
  selector: 'app',
  template: '<input type="text"  id="end_day" (change)="checkDates($event)" class="datepicker" datepicker>',
  directives: [ DatepickerDirective ]
})
export class App implements AfterViewInit {
  checkDates(e){
    console.log("Please, catch the change event ): "+e);
  }
}

See this plunkr: https://plnkr.co/edit/TVk11FsItoTuNDZLJx5X?p=preview

Upvotes: 1

Related Questions