0

J'utilise bootstrap-datepicker dans mon projet Angular en le créant en tant que directive. Voici mon code.Angular: Lier la date sélectionnée de bootstrap-datepicker au ngModel sous-jacent ou formControlName

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

config Datepicker dans le composant:

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

} 

Si je me concentre sur la zone de texte auquel j'ai appliqué cette directive, le datepicker apparaît, et quand je sélectionne une date, elle est affichée dans la zone de texte. Mais ce n'est pas lié au sous-jacent ngModel/formControlName. La variable correspondante est toujours undefined.

S'il vous plaît aidez-moi avec ceci.

Répondre

0

Je l'ai fait en utilisant ControlValueAccessor. Voici ma mise en œuvre.

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

}