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.

2
  • the jquery datepicker will override the change event of element with it's own logic, please refer stackoverflow.com/questions/27506111/… Commented Apr 25, 2016 at 12:58
  • Hi, thanks for your answer, but the problem is when I try to compile the file, I show an error like this one: "Object literal may only specify known properties, and 'onSelect' does not exist in type 'DatepickerOptions'" for this reason I can't compile the source code. Commented Apr 25, 2016 at 13:51

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Your answer doesn't work but you have you've taught me another way to use the angular 2 components! Thank's!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.