Angular: Bind date picked from bootstrap-datepicker to underlying ngModel or formControlName

大兔子大兔子 提交于 2019-12-13 03:33:40

问题


I'm using bootstrap-datepicker in my Angular project by creating it as a directive. Below is my code.

HTML: <input [datepicker]="datepickerConfig" readonly ngModel name="requestedDate" class="form-control" id="requestedDate" type="text">

Datepicker config in component:

datepickerConfig = {
    format: 'dd-M-yyyy'
};

Directive:

@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());
    }

}

If I focus on the textbox to which I've applied this directive, the datepicker pops up, and when I select a date, it's shown on the textbox. But it's not getting bound to the underlying ngModel / formControlName. The corresponding variable is still undefined.

Please help me with this.


回答1:


I did it using ControlValueAccessor. Below is my implementation.

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; }

}


来源:https://stackoverflow.com/questions/46709822/angular-bind-date-picked-from-bootstrap-datepicker-to-underlying-ngmodel-or-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!