如何在 Angular 17 中注册自定义管道?

问题描述 投票:0回答:1

我刚刚创建了一个自定义 Pipe,通常我会在 app.module.ts 中注册它,但在 Angular 17 中我们没有该文件。我们现在如何注册? TIA

我正在考虑像使用其他模块一样导入导入数组,但这不起作用。我尝试检查 angular.dev 网站,但由于某种原因它无法加载到我的笔记本电脑上。如有任何帮助,我们将不胜感激。

angular pipe angular17
1个回答
0
投票

对于独立组件,请在

imports
.component.ts
数组中注册自定义管道,如下所示:

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CustomPipe } from '../custom.pipe';

@Component({
  selector: 'app-test',
  standalone: true,
  imports: [CommonModule, CustomPipe], <-- register pipe here
  templateUrl: './test.component.html',
  styleUrl: './test.component.scss'
})
export class TestComponent { }

然后照常使用模板中的管道:

<p>{{ 'test' | customPipe }}</p>

假设自定义管道是这样的:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'customPipe',
  standalone: true
})
export class CustomPipe implements PipeTransform {

  transform(value: string): string[] {
    return value.split('');
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.