ngb-Datepicker中如何通过ngModel更新输入框日期?

How to update the input box date through ngModel in ngb-Datepicker?

我有一个使用 ngb-datepicker 作为日期的输入框。当我试图通过 ngModel 从日期选择器获取值时,它正在工作。但是当我尝试从函数更新 ngModel 时它不起作用,输入框没有更新。请找到下面的代码片段以供参考。

工作 stackblitz link 是 - Working Link 先从日历中选择日期然后在第二天更新模态中的值而不是在输入框中。

<!-- 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>

正如我在评论中所说,组件树中有一些点已设置 ChangeDetectionStrategy.OnPush。本例inside the ngb-datepicker source code,可以看出使用了这个策略

这意味着变化检测算法将在其较轻的版本中执行,并且只有在变量引用发生变化时才会触发更新。

因此,为了触发变化检测,您必须为变量分配一个新对象,而不是就地更改 属性。

您可以利用扩展运算符来获得更优雅的代码:

this.model = {...this.model, day: this.model.day+1};

或者以旧方式创建一个新对象:

this.model = Object.assign({}, this.model, {day: this.model.day+1});