面试题答案
一键面试在模板中展示
在模板中使用日期格式化管道如下:
<p>{{ myDate | date: 'yyyy - MM - dd' }}</p>
在组件类中导入和使用该管道
- 导入:在组件的
.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) {}
}
- 使用:在组件类中使用
DatePipe
对日期进行格式化。
formattedDate: string;
ngOnInit() {
this.formattedDate = this.datePipe.transform(this.myDate, 'yyyy - MM - dd');
}
然后在模板中可以这样展示:
<p>{{ formattedDate }}</p>
另外,在模块的 imports
数组中需要添加 CommonModule
,因为 DatePipe
是 CommonModule
的一部分。
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { YourComponent } from './your - component';
@NgModule({
imports: [
CommonModule
],
declarations: [YourComponent]
})
export class YourModule {}