I have made a DatePickerDirective
which is working fine as required. But in order to sync the value of the particular input field on which this directive sits, I have to use value and ngModel attribute both. I wish to use only ngModel how can this be achieved gracefully.
Form Element
<input appDatePicker type="text" required name="title" value="{{holiday.off_date}}" [(ngModel)]="holiday.off_date" class="form-control"
placeholder="01/01/2018">
Component File
export class HolidayCreateComponent implements OnInit, OnDestroy {
holiday = new HolidayModel('', '');
}
Model File
export class HolidayModel {
constructor(public occasion: string, public off_date: string) {
}
}
Directive File
import {Directive, ElementRef, forwardRef, OnInit} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
declare const $: any;
@Directive({
selector: '[appDatePicker]',
providers: [{
provide: NG_VALUE_ACCESSOR, useExisting:
forwardRef(() => DatePickerDirective),
multi: true
}]
})
export class DatePickerDirective implements OnInit, ControlValueAccessor {
value: string;
constructor(private el: ElementRef) {
}
ngOnInit() {
$(this.el.nativeElement).datepicker({
autoclose: true,
todayHighlight: true,
format: 'dd/mm/yyyy'
}).on('change', e => this._onChange(e.target.value));
}
private _onChange(_) {
}
private _onTouched(_) {
}
registerOnChange(fn: any): void {
this._onChange = fn;
}
registerOnTouched(fn: any): void {
this._onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
}
writeValue(val: string): void {
this.value = val;
}
}
The problem is whenever i try to manipulate value of date field from component i need use both value and ngmodel. I think this is not right can be improved. Is there anything which i forgot.
NOTE: the value and ngModel is required only where directive is used. If the input has no directive then ngModel works just perfect. I want the same behavior for the element with directive.