首页 > web前端 > js教程 > 正文

角管:综合指南

王林
发布: 2024-09-10 11:11:02
原创
906 人浏览过

Angular 中的

Angular Pipes: A Comprehensive guide

Pipes 是简单的函数,用于在不修改底层数据的情况下转换模板中的数据。管道接收一个值,对其进行处理,然后返回格式化或转换后的输出。它们通常用于格式化日期、数字、字符串,甚至数组或对象。

它们允许您直接在视图中以更具可读性或相关性的格式格式化和显示数据,而无需更改底层数据模型。

使用管道有助于保持代码干净可读。您可以将该逻辑封装在 pipe 中,而不是在模板或组件中编写复杂的逻辑,然后可以在应用程序的不同部分中重用该逻辑。
例如,如果您正在开发一个博客平台,用户可以在其中查看文章的发布日期。日期需要以用户友好的格式显示,例如“2024 年 8 月 31 日”,而不是原始格式“2024–08–31T14:48:00.000Z”。借助 pipes,您可以在模板中使用 Angular 内置的 DatePipe,而不是在组件中手动格式化日期,这会导致代码混乱并降低可读性。

<p>Published on: {{ article.publishDate | date:'longDate' }}</p>
登录后复制

要应用管道,请在模板表达式中使用 管道 运算符 (|),如上面的代码示例所示。

内置管道

Angular 附带了几个涵盖常见任务的内置管道(DatePipe、UpperCasePipe、LowerCasePipe、CurrencyPipe、AsyncPipe、JsonPipe、 等)。知道如何使用这些可以让你的代码更干净、更高效。

示例:

<pre class="brush:php;toolbar:false">{{ user | json }}

Price: {{ product.price | currency:'USD' }}

{{ user.name | uppercase }}

登录后复制

参数化管道

许多 Angular 管道接受参数来自定义其行为。

要指定参数,请在管道名称后面加上冒号 (:) 和参数值

一些管道接受多个参数,这些参数由额外的冒号分隔。

参数可以是可选必需。假设您有一个格式化货币的自定义管道,并要求您指定货币类型作为参数。如果未提供此参数,管道可能无法正确格式化该值。

<p>The product price is {{ price | customCurrency:'USD' }}</p>
登录后复制

1。带参数的 DatePipe

<p>Published on: {{ article.publishDate | date:'MMMM d, y, h:mm:ss a' }}</p>
登录后复制

这会将日期格式设置为“2024 年 8 月 31 日,下午 2:48:00”。

2。带参数的CurrencyPipe

<p>Price: {{ product.price | currency:'EUR':'symbol-narrow':'1.0-0' }}</p>
登录后复制

这会将价格格式化为“€1,235”(四舍五入到没有小数位)。

链接管道

您可以将多个管道链接在一起以实现复杂的转换。

<p>{{ article.content | slice:0:100 | uppercase }}</p>
登录后复制

这将分割 article.content 的前 100 个字符并将它们转换为大写。

定制管道

有时,内置管道可能无法满足您的特定需求,您需要创建自定义管道来处理特定逻辑。具体方法如下。

示例:

在下面的示例中,我们将创建一个管道,为诸如“Hello, Alice!”之类的名称添加问候语

运行以下命令生成新管道:

ng generate pipe greet
登录后复制

现在,让我们修改 src/app 目录中的greet.pipe.ts 文件以包含管道逻辑:

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

@Pipe({
  name: 'greet',  // This is the name you'll use in the template
  standalone: true,
})
export class GreetPipe implements PipeTransform {
  transform(value: string): string {
    return `Hello, ${value}!`;  // This is the transformation logic
  }
}
登录后复制

管道准备好后,您就可以在模板中使用它。

<p>{{ 'Alice' | greet }}</p>
登录后复制

创建参数化自定义管道

现在我们要自定义问候语,这样你就可以说“嗨,爱丽丝!”或“欢迎,爱丽丝!”取决于您传递给管道的内容。

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

@Pipe({
  name: 'greet',  // Same pipe name as before
  standalone: true,
})
export class GreetPipe implements PipeTransform {
  transform(value: string, greeting: string = 'Hello'): string {
    return `${greeting}, ${value}!`;  // Now it uses the greeting passed in
  }
}
登录后复制

transform 方法现在有第二个参数,greeting。如果没有提供问候语,则默认为“Hello”。

现在您可以在模板中自定义问候语。

<p>{{ 'Alice' | greet:'Hi' }}</p>
<p>{{ 'Bob' | greet:'Welcome' }}</p>
登录后复制

纯净管道与不纯净管道

1。纯管
默认情况下,所有 Angular 管道都是纯管道仅在输入数据(如数字或字符串)或对对象的引用(如数组或日期)更改时被调用。这使得纯管道变得高效且高性能,因为管道不会不必要地运行。

但是,如果您的数据更复杂,例如项目数组,Angular 可能不会注意到数组内部的更改(例如添加新项目),因为对数组的引用没有更改。

除非必要,请保持管道纯净以避免不必要的重新渲染并保持性能。

示例:

@Pipe({
  name: "onSale",
  standalone: true,
  pure: true,
})
export class OnSalePipe implements PipeTransform {
  transform(items: Item[]): Item[] {
    return items.filter((item) => item.isOnSale);
  }
}
登录后复制

在您的模板中:

<ul>
  <li *ngFor="let item of (items | onSale)">
    {{ item.name }} - {{ item.price | formatPrice }}
  </li>
</ul>
登录后复制

If you add a new item to the items array that’s on sale, you might expect it to show up in the list. But if you simply push the new item into the array, the list might not update because the array reference hasn’t changed.

2. Impure Pipes

An impure pipe, on the other hand, is called every time Angular performs a change detection cycle. However, because they run so often, they can slow down your app.

Example:

@Pipe({
  name: "onSaleImpure",
  standalone: true,
  pure: false,
})
export class OnSaleImpurePipe implements PipeTransform {
  transform(items: Item[]): Item[] {
    return items.filter((item) => item.isOnSale);
  }
}
登录后复制

In your template:

<ul>
  <li *ngFor="let item of (items | onSaleImpure)">
    {{ item.name }} - {{ item.price | formatPrice }}
  </li>
</ul>
登录后复制

Now, when you add a new item, the pipe will notice the change and update the list.

Best Practices for Using Pipes

  1. Keep Pipes Simple. Avoid Heavy Computations in Pipes

  2. Name Pipes Clearly and Descriptively

  3. Keep Pipes Focused on a Single Responsibility

  4. Avoid Impure Pipes When Possible

  5. Test Custom Pipes Thoroughly

Conclusion

Angular pipes streamline data transformation tasks, making your code more modular, reusable, and maintainable. They help to enforce consistency across the application and improve the readability of your templates, which is crucial for developing scalable and maintainable applications.

以上是角管:综合指南的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!