I'm using reactive forms in my Angular 2 webapp and I'm having troubles assigning the date to ngbDatepicker (ngbootstrap 1 alpha 6). My object has a date object such as:
var myObject = {date: new Date(1, 9, 2016)};
and in my reactive form, it is configured as follow:
input.form-control(name='date', ngbDatepicker, #date="ngbDatepicker", placeholder='jj.mm.aaaa', formControlName='date', type="text")
and I patch the form like this:
this.form.patchValue({myObject: myObject});
The problem is that ngbDatepicker
take the date with the following structure:
{day: DD, month: MM, year: YYYY}
I have found a workaround that does:
this.form.controls.myObject.controls.date.valueChanges
.map((value) => {
if(value) {
if (typeof value.getMonth === 'function') {
this.form.controls.myObject.patchValue({
date: {
day: value.getUTCDay(),
month: value.getUTCMonth(),
year: value.getUTCFullYear()
}
});
}
}
return value;
})
.subscribe((value) => {
});
And everything works as expected (the date gets updated whenever form gets patched) but it is way too verbose (18 lines of code) and my form has a dozen of dates!
So my question is can I achieve the same result with a much shorter solution?
I don't know if it might help you
ng-bootstrap: 1
angular: 2
bootstrap: 4
ngOnInit() {
const now = new Date();
const since = moment().subtract(14,'d').toDate();
this.model.fechaHasta = {year: now.getFullYear(), month: now.getMonth() + 1, day: now.getDate()};
this.model.fechaDesde = {year: since.getFullYear(), month: since.getMonth() + 1, day: since.getDate()};
}
HTML
<div class="input-group">
<input class="form-control" placeholder="yyyy-mm-dd"
name="fechaHasta" [(ngModel)]="model.fechaHasta" ngbDatepicker #d10="ngbDatepicker">
<div class="input-group-addon" (click)="d10.toggle()">
<img src="../../shared/img/calendar-icon.png" style="width: 1.2rem; height: 1rem; cursor: pointer;"/>
</div>
</div>