关于 angular-pipes
面向使用管道转换和格式化模板值的 Angular 开发者的参考技能。内容涵盖内置与自定义管道、异步数据,以及纯管道和新版管道 API 的使用建议。
主要功能
- 01转换模板中的值
- 02带参数及链式管道
- 03用于 Observable 的异步管道
- 04独立管道与信号管道
- 05在管道中使用 inject() 注入依赖
适用场景
- 01在模板中格式化值
- 02在模板中显示 Observable 数据
- 03遍历对象条目或检查 JSON
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ oguzhan18/ angular-ecosystem-skills --skill angular-pipes安装后在 Claude Code 中输入/angular-pipes确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/discussions/_INDEX.mdreferences/docs/_INDEX.mdreferences/issues/_INDEX.mdreferences/releases/_INDEX.md详细介绍
Angular 管道
版本: Angular 21(2025) 标签: 管道、转换、格式化、异步
API 变更
本节记录近期特定版本的 API 变更。
-
新增:独立管道 — 所有管道都可以是独立的
-
新增:基于信号的管道 — 管道可以使用信号
-
新增:管道中的 inject() — 在管道中使用函数式 DI
-
已弃用:非纯管道 — 为提升性能,请避免使用;改用纯管道
最佳实践
- 对无状态转换使用纯管道
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'capitalize',
standalone: true
})
export class CapitalizePipe implements PipeTransform {
transform(value: string): string {
if (!value) return '';
return value.charAt(0).toUpperCase() + value.slice(1);
}
}
- 在模板中使用管道
@Component({
template: `
<p>{{ name | capitalize }}</p>
<p>{{ price | currency:'USD' }}</p>
<p>{{ items | json }}</p>
`
})
export class MyComponent {}
- 使用带参数的管道
@Pipe({ name: 'slice' })
export class SlicePipe implements PipeTransform {
transform(value: string, start: number, end?: number): string {
return value.slice(start, end);
}
}
// Usage: {{ text | slice:0:10 }}
- 对可观察对象使用 async 管道
@Component({
template: `
@if (user$ | async; as user) {
<p>{{ user.name }}</p>
}
`
})
export class UserComponent {
user$ = this.userService.getUser();
}
- 仅在必要时使用非纯管道
@Pipe({
name: 'myPipe',
pure: false // Impure - runs on every change detection
})
export class ImpurePipe implements PipeTransform {}
- 使用 KeyValue 管道迭代对象
@Component({
template: `
@for (item of object | keyvalue; track item.key) {
{{ item.key }}: {{ item.value }}
}
`
})
export class MyComponent {
object = { a: 1, b: 2 };
}
- 使用 Json 管道进行调试
@Component({
template: `
<pre>{{ object | json }}</pre>
`
})
export class DebugComponent {}
- 链接管道
@Component({
template: `
{{ name | uppercase | slice:0:5 }}
`
})
export class ChainedPipeComponent {}
- 在 imports 中使用独立管道
@Component({
standalone: true,
imports: [DatePipe, CurrencyPipe, CapitalizePipe],
template: `{{ date | date }}`
})
export class MyComponent {}
- 在管道中使用 inject()
@Pipe({ name: 'translate', standalone: true })
export class TranslatePipe implements PipeTransform {
private service = inject(TranslateService);
transform(key: string): string {
return this.service.get(key);
}
}
评论
支持 Markdown