Lucas Everett Lucas Everett - 5 months ago 106
jQuery Question

How do you update model from directive in Angular 2?

How do I update my model upon change from Jquery Datepicker? If I manually type into the

<input>
the model updates, but the model doesn't update after making a selection from the Jquery Datepicker popup. The
<input>
value updates with the selected date, but the model doesn't change.

I've tried wrapping the datepicker() in a timeout, but that doesn't work either. How can I make the model aware of the change in the directive?

Input in Component Template:


<input type="text" class="datepicker" [(ngModel)]="foreigndate" datepicker>


Directive:


@Directive({
selector: '[datepicker]'
})
export class DatePickerDirective {
constructor(el: ElementRef) {
$(el.nativeElement).datepicker();
}
}

Answer

[(ngModel)] updates foreigndate when input is fired which seems not to be the case when datepicker updates the value.

http://api.jqueryui.com/datepicker/ doesn't provide any information about events fired when the value changes.

If it would you could use this workaround

<input type="text" class="datepicker" [(ngModel)]="foreigndate" datepicker (someEvent)="foreigndate=$event.target.value">

Listening to the change event this way might be worth a try.

Otherwise this should work

<input #datepicker type="text" class="datepicker" [(ngModel)]="foreigndate" datepicker>
@ViewChild('datepicker') datePicker:ElementRef;

ngDoCheck() {
  this.foreigndate = this.datePicker.nativeElement.value;
}
Comments