In Angular 17, the
compute()
Example of Using compute()
Let's say you have a simple application that manages a list of items and you want to compute the total price of these items.
Step 1: Setting Up Signals
First, create your basic signals for the item list and the individual item prices.
typescripimport { signal, computed } from '@angular/core';
// Signal for item prices
const itemPrices = signal<number[]>([10, 20, 30]);
// Signal for tax rate
const taxRate = signal<number>(0.1);
Step 2: Create a Derived Signal
Now, use the computed()
API to derive the total price with tax.
typescriptconst totalPrice = computed(() => {
const prices = itemPrices();
const tax = taxRate();
const total = prices.reduce((sum, price) => sum + price, 0);
return total + (total * tax);
});
Step 3: Using the Signals
You can now use these signals in your component. Here's how you can display the total price and modify the item prices.
typescriptimport { Component } from '@angular/core';
@Component({
selector: 'app-item-list',
template: `
<div>
<h1>Total Price: {{ totalPrice() }}</h1>
<button (click)="addItem()">Add Item ($40)</button>
<button (click)="updateTaxRate()">Update Tax Rate (20%)</button>
</div>
`,
})
export class ItemListComponent {
constructor() {}
addItem() {
const prices = itemPrices();
itemPrices.set([...prices, 40]);
}
updateTaxRate() {
taxRate.set(0.2);
}
}
Explanation
- Signals:
itemPrices
andtaxRate
are signals holding the state of the item prices and the tax rate. - Computed Signal:
totalPrice
computes the total by summing up the prices and applying the tax. - Component: The component displays the total price and provides buttons to add an item and update the tax rate.
Benefits of Derived Signals
- Reactivity: The
totalPrice
will automatically recalculate wheneveritemPrices
ortaxRate
changes, ensuring that your UI stays in sync with the underlying data. - Performance: Derived signals are efficient as they only recompute when their dependencies change.
This pattern is powerful for building responsive, reactive Angular applications.
No comments:
Post a Comment