首頁 > 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學習者快速成長!