【问题标题】:How can I get my Angular2 DatePipe-formatted Date to update?如何让我的 Angular2 DatePipe 格式的日期更新?
【发布时间】:2016-11-10 21:57:48
【问题描述】:

问题示例:http://plnkr.co/edit/7FeRoyyqDnjXpV9Q9Vpy?p=preview

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>{{myDate}}</h2> <!-- THIS UPDATES AS EXPECTED -->
      <h2>{{myDate | date: 'longDate'}}</h2> <!-- THIS DOES NOT -->
      <a (click)="prevMonth()" href="javascript:;">Previous Month</a>
      <a (click)="nextMonth()" href="javascript:;">Next Month</a>
    </div>
  `,
})
export class App {
  myDate: Date;
  constructor() {
    this.myDate = new Date();
  }

  nextMonth() {
    this.myDate.setMonth(this.myDate.getMonth() + 1);
  }

  prevMonth() {
    this.myDate.setMonth(this.myDate.getMonth() - 1);
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

当我在不使用任何管道的情况下传递我的变量时,它会按预期更新。但是同一变量的 DatePipe 格式的副本不会更新。管道是否仅针对可观察对象进行更新?或者我可以将它与标准日期类型一起使用并期望它实时更新吗?

我在 DatePipe API 中没有看到任何暗示这是预期行为的内容,但我已将其范围缩小到只有 DatePipe 可能以这种方式影响行为的程度。 https://angular.io/docs/ts/latest/api/common/index/DatePipe-pipe.html

【问题讨论】:

    标签: angular angular2-pipe


    【解决方案1】:

    它不起作用,因为 Angular2 的 DatePipe 是有状态的(装饰函数中的 pure 属性设置为 true)。有状态管道仅在给定对象上应用一次。您可以更改管道定义(当然不是在 A2 源中)或做一些事情来强制更改数据。

    所以解决它的第一种方法是创建和使用新的无状态管道:

    @Pipe({name: 'myDate', pure: false})
    export class MyDatePipe implements PipeTransform {
      transform(value: any, pattern: string = 'mediumDate'): string {
        return (new DatePipe()).transform(value, pattern);
      }
    }
    

    我准备了plnkr example。 它简单且可重复使用,因此我会向小数据推荐此解决方案。

    虽然,也可以在每次更新日期后使用ChangeDetector 及其markForCheck() 方法来解决 - 这会更有效。 或者正如 Dmitry 所说,每次要更改数据时只需创建新的日期对象。

    【讨论】:

      【解决方案2】:

      您需要使用新的日期参考重新分配日期变量。

      this.myDate = new Date(this.myDate.setMonth(this.myDate.getMonth() + 1));

      如文档中所述

      这个管道被标记为纯的,因此当输入发生突变时它不会被重新评估。相反,用户应将日期视为不可变对象,并在管道需要重新运行时更改引用

      【讨论】:

        【解决方案3】:

        似乎管道不是在更新链接对象之后而是在更新对象链接之后触发更新。

        您可以通过重新分配 this.myDate 来修复它,如下所示:

        this.myDate = new Date(this.myDate.setMonth(this.myDate.getMonth() + 1));

        【讨论】:

          猜你喜欢
          • 2017-01-03
          • 1970-01-01
          • 1970-01-01
          • 2021-12-25
          • 2016-06-09
          • 1970-01-01
          • 1970-01-01
          • 2011-04-22
          • 1970-01-01
          相关资源
          最近更新 更多