【问题标题】:How to update the input box date through ngModel in ngb-Datepicker?ngb-Datepicker中如何通过ngModel更新输入框日期?
【发布时间】:2018-12-06 10:31:57
【问题描述】:

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

工作 stackblitz 链接是 - 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
  • 你能在 StackBlitz 上创建一个示例吗?
  • 我在问题中给出了一个链接——“工作链接”
  • 对不起,我错过了

标签: javascript angular typescript ngb-datepicker


【解决方案1】:

正如我在评论中所说,组件树中的某个点已设置为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});

【讨论】:

  • 这是完美的克里斯蒂安。有了这么好的解释。多谢了。
  • 我用它来填充我的日期字段。当控制台模型值正确但输入框值不变时。
  • goooooddd,它与 Object.assign({}) 一起使用来设置 null
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-11
相关资源
最近更新 更多