MST

星途 面试题库

面试题:Angular中日期格式化管道的基本使用

在Angular项目中,假设你有一个日期对象 `let myDate = new Date();`,请使用日期格式化管道将其格式化为 'yyyy - MM - dd' 的形式并在模板中展示,同时说明如何在组件类中导入和使用该管道。
20.6万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

在模板中展示

在模板中使用日期格式化管道如下:

<p>{{ myDate | date: 'yyyy - MM - dd' }}</p>

在组件类中导入和使用该管道

  1. 导入:在组件的 .ts 文件中,从 @angular/common 中导入 DatePipe
import { Component } from '@angular/core';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'app - your - component',
  templateUrl: './your - component.html',
  styleUrls: ['./your - component.css']
})
export class YourComponent {
  myDate = new Date();
  constructor(private datePipe: DatePipe) {}
}
  1. 使用:在组件类中使用 DatePipe 对日期进行格式化。
formattedDate: string;
ngOnInit() {
  this.formattedDate = this.datePipe.transform(this.myDate, 'yyyy - MM - dd');
}

然后在模板中可以这样展示:

<p>{{ formattedDate }}</p>

另外,在模块的 imports 数组中需要添加 CommonModule,因为 DatePipeCommonModule 的一部分。

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { YourComponent } from './your - component';

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [YourComponent]
})
export class YourModule {}