面试题答案
一键面试- 创建自定义管道:
- 使用Angular CLI命令
ng generate pipe dateFormat
来生成一个名为dateFormat
的管道。这会在src/app
目录下创建date - format.pipe.ts
文件。
- 使用Angular CLI命令
- 编写管道逻辑:
- 在
date - format.pipe.ts
文件中,导入必要的模块:
- 在
import { Pipe, PipeTransform } from '@angular/core';
- 定义管道类并实现
PipeTransform
接口:
@Pipe({
name: 'dateFormat'
})
export class DateFormatPipe implements PipeTransform {
transform(value: string): string {
const date = new Date(value);
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const year = date.getFullYear();
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
return `${month}/${day}/${year} ${hours}:${minutes}`;
}
}
- 在组件模板中使用管道:
- 假设在组件中有一个变量
dateValue
存储后端返回的日期字符串,在模板中可以这样使用:
- 假设在组件中有一个变量
<p>{{ dateValue | dateFormat }}</p>
- 注册管道:
- 如果管道在
app.module.ts
所在的模块中,需要在declarations
数组中注册该管道:
- 如果管道在
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform - browser';
import { AppComponent } from './app.component';
import { DateFormatPipe } from './date - format.pipe';
@NgModule({
declarations: [
AppComponent,
DateFormatPipe
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
关键代码总结:
- 管道逻辑:
@Pipe({
name: 'dateFormat'
})
export class DateFormatPipe implements PipeTransform {
transform(value: string): string {
const date = new Date(value);
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const year = date.getFullYear();
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
return `${month}/${day}/${year} ${hours}:${minutes}`;
}
}
- 模板使用:
<p>{{ dateValue | dateFormat }}</p>
- 模块注册:
@NgModule({
declarations: [
// 其他组件
DateFormatPipe
],
// 其他模块配置
})
export class AppModule { }