I have an input box which uses ngb-datepicker for the date. When I am trying to get the value from date picker through ngModel, it is working. But it is not working when I am trying to update ngModel from the function, input box is not getting updated. Please find the snippet below just for reference.
working stackblitz link is - Working Link Selecting the date from calendar first and then the next day is updating the value in modal but not in the input box.
<!-- typescript code -->
import {Component} from '@angular/core';
@Component({
selector: 'ngbd-datepicker-popup',
templateUrl: './datepicker-popup.html'
})
export class NgbdDatepickerPopup {
model ;
nextDay() {
this.model.day = this.model.day +1 ;
}
}
<!-- Html code -->
<form class="form-inline">
<div class="form-group">
<div class="input-group">
<input class="form-control" placeholder="yyyy-mm-dd"
name="dp" [(ngModel)]="model" ngbDatepicker #d="ngbDatepicker">
<div class="input-group-append">
<button class="btn btn-outline-secondary calendar" (click)="d.toggle()" type="button"></button>
</div>
</div>
</div>
</form>
<hr/>
<button class="btn btn-sm btn-outline-primary mr-2" (click)="nextDay()">Next Day</button>
<pre>Model: {{ model | json }}</pre>
As I said in the comment, there is some point in the component tree where has been set ChangeDetectionStrategy.OnPush
. In this case, inside the ngb-datepicker
source code, you can see that this strategy is used.
This means that the change detection algorithm will be executed in its lighter version, and it will trigger an update only if the variable reference is changed.
So, in order to trigger change detection, you have to assign a new object to the variable rather than changing the property in place.
You can take advantage of the spread operator to have a more elegant code:
this.model = {...this.model, day: this.model.day+1};
Or just create a new object in the old style way:
this.model = Object.assign({}, this.model, {day: this.model.day+1});