AngularJS 2输入字段不会为jQuery Date Picker日期更改更新ngModel [英] AngularJS 2 input field does not update ngModel for Jquery Date Picker date change

查看:145
本文介绍了AngularJS 2输入字段不会为jQuery Date Picker日期更改更新ngModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

angularjs 2组件中的Jquery UI datepicker出现问题.

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

它显示从日期日历更改的日期,但不更新基础ngModel:dateSelected.

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"/>

我正在尝试将this.dateSelected模型中的选定日期设置为第二个日期选择器,这将不起作用.

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

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

另一方面,如果我通过jQuery val方式读取选定的日期,则效果很好.

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

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

这是代码插入器: https://plnkr.co/edit/iLAFa8yrCLeTcd27G8bY?p=预览

可以帮忙吗?

推荐答案

更新

也许您想编写将实现ControlValueAccessor的自定义指令:

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

来源

我认为您可以使用以下方法来做到这一点:

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

这篇关于AngularJS 2输入字段不会为jQuery Date Picker日期更改更新ngModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆