1
votes

I am having a problem with Jquery UI datepicker in angularjs 2 component.

It displaying changed date from date calender but its not updating underlying ngModel : dateSelected.

dateSelected: string = '';

Here the date picker input filed is:

<input type="text" class="form-control" [(ngModel)]="dateSelected" name='datepicker1' id='datepicker1' placeholder="Select a date"/>

And I am trying set the selected date from this.dateSelected model to second date picker which does not work.

$("#datepicker2").val(this.dateSelected);

On the other hand if I read selected date by JQuery val way it works fine.

  var selectedDateInPicker = $("#datepicker1").val();     
   $("#datepicker2").val(selectedDateInPicker);

Here is the code plunker: https://plnkr.co/edit/iLAFa8yrCLeTcd27G8bY?p=preview

Can you please help?

1

1 Answers

5
votes

Update

Maybe you want to write custom directive that will implement ControlValueAccessor:

declare var $: any;

@Directive({
  selector: '[datepicker]',
  providers: [{
    provide: NG_VALUE_ACCESSOR,useExisting: 
    forwardRef(() => DatePickerDirective),
    multi: true
  }]
})
export class DatePickerDirective implements ControlValueAccessor {  
    value: string;

    constructor(protected el: ElementRef) {}

    ngAfterViewInit(){
      $(this.el.nativeElement).datepicker({
        changeMonth: true, 
        yearRange: "1:100", // you can pass it as @Input options  
        changeYear: true
      }).on('change', e => this.onModelChange(e.target.value));
    } 

    onModelChange: Function = () => {};

    onModelTouched: Function = () => {};

    writeValue(val: string) : void {
        this.value = val;
    }

    registerOnChange(fn: Function): void {
        this.onModelChange = fn;
    }

    registerOnTouched(fn: Function): void {
        this.onModelTouched = fn;
    }
}

Plunker Example

Origin

I think you can do it working by using the following:

$(selector-ng-datepicker).datepicker({
  changeMonth: true,
  yearRange: "1:100",
  changeYear: true
}).on('change', e => this.dateSelected = e.target.value);

Updated Plunker