我在Angular项目中使用bootstrap-datepicker创建它作为指令。以下是我的代码。
HTML:
<input [datepicker]="datepickerConfig" readonly ngModel name="requestedDate" class="form-control" id="requestedDate" type="text">
组件中的Datepicker配置:
datepickerConfig = {
format: 'dd-M-yyyy'
};
指令:
@Directive({ selector: '[datepicker]' })
export class DatepickerDirective implements OnInit {
@Input() datepicker;
constructor(private el: ElementRef) { }
ngOnInit() {
$(this.el.nativeElement).datepicker(this.datepicker);
$(this.el.nativeElement).next('.input-group-addon').find('.glyphicon-calendar')
.click(() => $(this.el.nativeElement).focus());
}
}
如果我专注于我已应用此指令的文本框,则弹出日期选择器,当我选择日期时,它会显示在文本框中。但它并没有受到基础ngModel
/ formControlName
的约束。相应的变量仍为undefined
。
请帮助我。
答案 0 :(得分:0)
我是使用ControlValueAccessor
完成的。以下是我的实施。
import { Directive, ElementRef, Input, OnInit, HostListener, forwardRef } from '@angular/core';
import { DatePipe } from '@angular/common';
import 'bootstrap-datepicker';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Directive({
selector: '[datepicker]',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => DatepickerDirective),
multi: true
},
DatePipe
]
})
export class DatepickerDirective implements OnInit, ControlValueAccessor {
@Input() datepicker;
constructor(private el: ElementRef, private datePipe: DatePipe) { }
ngOnInit() {
$(this.el.nativeElement).datepicker(this.datepicker);
$(this.el.nativeElement).next('.input-group-addon').find('.glyphicon-calendar')
.click(() => $(this.el.nativeElement).focus());
}
// ControlValueAccessor interface
private _onChange = (_) => { };
private _onTouched = () => { };
@HostListener('blur', ['$event'])
input(event) {
this._onChange(event.target.value);
this._onTouched();
}
writeValue(value: any): void {
$(this.el.nativeElement).val(this.datePipe.transform(value, 'dd-MMM-yyyy'));
}
registerOnChange(fn: (_: any) => void): void { this._onChange = fn; }
registerOnTouched(fn: any): void { this._onTouched = fn; }
}