应用程序中用于 HTML 文件标签的通用日期格式

问题描述 投票:0回答:2

我正在更新 Angular 中的应用程序。

我想将日期的格式设置为应用程序的通用值。

换句话说,我希望将格式作为字符串,作为常量存储在某处,或者作为全局字符串/设置。

到目前为止,我有:

<p>{{creationDate | date: 'd/M/y, hh:mm'}}</p>

我真正需要的就是将

'd/M/y, hh:mm'
作为某个地方的存储值,然后我可以在任何 HTML 文件中使用它。就此而言,从 ts 文件中的全局位置获取它对我来说没问题。

如何将格式设置为变量或常量?

angular angularjs
2个回答
2
投票

假设您使用 AngularJS,您可以将日期格式放入作用域中的变量中,或者使用模块

.constant()
并注入它:

angular.module("exampleApp", [])
  .constant("dateFmt", "d/M/y, hh:mm")
  .controller("dateFmtCtrl", function($scope, dateFmt) {
    $scope.creationDate = new Date();
    $scope.dateFmt = dateFmt;
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.js"></script>
<div ng-app="exampleApp" ng-controller="dateFmtCtrl">
  <p>{{creationDate | date: dateFmt}}</p>
</div>


2
投票

创建共享服务:date-format.service.ts

import { Injectable } from '@angular/core';
        
        @Injectable({
          providedIn: 'root',
        })
        export class DateFormatService {
          dateFormat: string = 'd/M/y, hh:mm';
        }

将服务注入组件中:

import { Component } from '@angular/core';
    import { DateFormatService } from './date-format.service';
    
    @Component({
      selector: 'app-my-component',
      template: '<p>{{creationDate | date: dateFormat}}</p>',
    })
    export class MyComponent {
       creationDate: Date;
  dateFormat: string;

  constructor(private dateFormatService: DateFormatService) {
    this.creationDate = new Date();
    this.dateFormat = this.dateFormatService.dateFormat; // Access the dateFormat property from the service
   
  }
    }
© www.soinside.com 2019 - 2024. All rights reserved.