【问题标题】:How to use an Angular pipe with complex parameters from the HTML template?如何使用来自 HTML 模板的复杂参数的 Angular 管道?
【发布时间】:2021-10-22 04:44:06
【问题描述】:

我正在制作一个国际化的 Angular 应用程序,因此我为我的 MatDatepickers 实现了MatLuxonDateModule,它运行良好。但我也想在格式化日期时使用 Luxon 管道而不是内置日期管道,以便它在所有浏览器和文化中始终如一地工作。

我做了一个很好用的:

import { Pipe, PipeTransform } from '@angular/core';
import { DateTime, DateTimeFormatOptions } from 'luxon';

@Pipe({
  name: 'dateFormat',
})
export class LuxonDatePipe implements PipeTransform {
  transform(value: DateTime | Date, format: DateTimeFormatOptions = DateTime.DATE_SHORT): any {
    let dateTimeToUse: DateTime;
    if (value instanceof Date) {
      dateTimeToUse = DateTime.fromJSDate(value);
    } else {
      dateTimeToUse = value;
    }

    return dateTimeToUse.toLocaleString(format);
  }
}

现在我想在 HTML 模板中使用它,像这样:

{{ testDate | dateFormat: DateTime.DATE_MED_WITH_WEEKDAY }}

...但它不知道“日期时间”是什么。我可以通过将其更改为来解决这个问题:

{{ testDate | dateFormat: formatToUse }}

...但是每次我需要格式化日期时,我都必须在 .ts 文件中声明这样的属性:

  formatToUse: DateTimeFormatOptions = DateTime.DATE_MED_WITH_WEEKDAY;

这真的很麻烦。 有没有办法在模板中“导入”Luxon,以便我可以即时引用 DateTime

编辑:我想我可以将参数更改为字符串并向管道添加一个巨大的开关盒以映射到 Luxon 格式,但这似乎不太理想。

【问题讨论】:

  • 我认为DateTime 是一个枚举,所以如果你想使用它,你必须将洞枚举设置为你的组件中的一个对象,比如public eDateTime = DateTime,然后你可以像{{ testDate | dateFormat: eDateTime.DATE_MED_WITH_WEEKDAY }} 这样使用它
  • @DerHerrGammler 这绝对比我拥有的要好。如果我想不出办法做到这一点而根本不必接触 .ts 文件,我会这样做。

标签: angular luxon


【解决方案1】:

试试这个:

更换管道:

export class LuxonDatePipe implements PipeTransform {
  transform(value: DateTime | Date, format: string = 'DATE_SHORT'): any {
    let dateTimeToUse: DateTime;
    if (value instanceof Date) {
      dateTimeToUse = DateTime.fromJSDate(value);
    } else {
      dateTimeToUse = value;
    }

    return dateTimeToUse.toLocaleString((<any>DateTime)[format]);
  }
}

并像这样使用你的管道:

{{ testDate | dateFormat: 'DATE_MED_WITH_WEEKDAY' }}

【讨论】:

  • 我喜欢自动转换字符串的想法,但它说“在 'typeof DateTime' 类型上没有找到带有 'string' 类型参数的索引签名。”
  • 抱歉没用。
  • 其实你们很亲近!如果我遵循第一条评论here,则可以使用。我会编辑并接受。
  • 如此接近!我很高兴它能帮助你。
猜你喜欢
  • 2020-05-15
  • 2022-01-17
  • 1970-01-01
  • 2020-09-26
  • 1970-01-01
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多