typescript Angular date pipe在HTML中无法正常工作

flseospp  于 2023-06-07  发布在  TypeScript
关注(0)|答案(1)|浏览(286)

角管不工作
我正在尝试使用Angular的日期管道。由于某种原因,我似乎无法让它工作。我尝试了几种方法,比如在通过管道传递日期之前将其更改为字符串,或者将管道放在HTML中的其他地方,但似乎不起作用。任何建议都非常感谢(:
组件HTML文件

<h1>My todos</h1>

<table border="1">
  <caption>Fun times ahead</caption>
  <caption>{{testDate}}</caption>
  <caption>{{testDate2 | date}}</caption>
  <thead>
    <tr>
      <th>Description</th>
      <th>Target Completion Date</th>
      <th>Is it done?</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let todo of todos">
      <th>{{todo.description}}</th>
      <th>{{todo.targetDate}}</th>
      <th *ngIf="todo.done">Yes</th>
      <th *ngIf="!todo.done">No</th>
    </tr>
  </tbody>
</table>

组件TS文件

import { Component, OnInit } from '@angular/core';

export class Todo{
  constructor(public id:number, public description:string, public done:boolean, public targetDate:String){

  }
}

@Component({
  selector: 'app-list-todos',
  templateUrl: './list-todos.component.html',
  styleUrls: ['./list-todos.component.css']
})
export class ListTodosComponent implements OnInit{

  testDate : String = new Date(2010, 1, 1).toDateString()
  testDate2 : String = new Date(2010, 1, 2).toDateString()

  todos = [
    new Todo(1, 'ex1', true, new Date().toDateString()),
    new Todo(2, 'ex2', false, new Date().toDateString()),
    new Todo(3, 'ex3', false, new Date().toDateString()),
    new Todo(4, 'ex4', false, new Date().toDateString()),
    new Todo(5, 'ex5', false, new Date().toDateString()),
    new Todo(6, 'ex6', false, new Date().toDateString()),
  ]

  constructor() {

  }

  ngOnInit(){

  }

}
af7jpaap

af7jpaap1#

导入DatePipe模块并在组件的构造函数中注入DatePipe。现在应该将日期管道应用于表中每个todo对象的targetDate属性,根据您的区域设置格式化日期

import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';

export class Todo {
  constructor(
    public id: number,
    public description: string,
    public done: boolean,
    public targetDate: string
  ) {}
}

@Component({
  selector: 'app-list-todos',
  templateUrl: './list-todos.component.html',
  styleUrls: ['./list-todos.component.css'],
  providers: [DatePipe] // Add DatePipe as a provider
})
export class ListTodosComponent implements OnInit {
  testDate: string = new Date(2010, 1, 1).toDateString();
  testDate2: string = new Date(2010, 1, 2).toDateString();

  todos = [
    new Todo(1, 'ex1', true, new Date().toDateString()),
    new Todo(2, 'ex2', false, new Date().toDateString()),
    new Todo(3, 'ex3', false, new Date().toDateString()),
    new Todo(4, 'ex4', false, new Date().toDateString()),
    new Todo(5, 'ex5', false, new Date().toDateString()),
    new Todo(6, 'ex6', false, new Date().toDateString()),
  ];

  constructor(private datePipe: DatePipe) {}

  ngOnInit() {}
}

使用模板中的DatePipe设置日期格式:在模板中,使用datePipe来格式化日期,而不是直接访问todo对象的targetDate属性。将显示目标日期的行修改为
HTML

<th>{{ todo.targetDate | date }}</th>

希望对你有帮助。

相关问题