Reputation: 1675
I have an angular application using the following model class:
export interface Product {
id: number;
name: string;
currentPrice: number;
orders?: Order[];
lastUpdate?: Date;
}
export interface Order {
orderId: string;
qty: number;
amount: number;
}
I would like to add a note on UI when user adds an order. However, angular does not fire change detection without updating object reference of the product.
Replicated on: https://stackblitz.com/edit/ag-grid-angular-use-gridoptions-k75cr8?file=src/app/order.component.ts
"Add Order" button does not add an entry of "Product / Order updated on hh:mm:sss". "Add Order & Change reference" button adds an entry of it.
Why do I need to update reference of the model to fire change detection? (why does the order table still gets updated without triggering change detection on click of "Add Order" button)
Upvotes: 1
Views: 2724
Reputation: 3171
I would like to add a note on UI when user adds an order. However, angular does not fire change detection without updating object reference of the product.
In your example Angular does run Change Detection when you click "Add Order" button, and that's why the table within OrderComponent reflects the newly added order.
"Add Order" button does not add an entry of "Product / Order updated on hh:mm:sss". "Add Order & Change reference" button adds an entry of it.
"Add Order" button doesn't add an entry because the @Input()
setter associated with product is not called. Why it's not called? Because Angular performs reference check, and doesn't find any change in the property binding. So it doesn't update the binding.
In case of "Add Order & Change reference" you are changing the reference, and hence Angular will update the binding, which in turn calls the @Input
setter which updates the this.notes
value.
Why do I need to update reference of the model to fire change detection? (why does the order table still gets updated without triggering change detection on click of "Add Order" button)
You don't need to update the reference to trigger Change Detection when using Default
ChangeDetectionStrategy. Why order table gets updated, is because of Change Detection.
Upvotes: 2
Reputation: 402
Since you get the answer about reference issues that can work without updating the reference;
you can send orders as input, and you can hold the orderedDate information inside the order. Here is the updated stack blitz;
If you still want to send the product you can update the inputs accordingly, that will work too.
Upvotes: 0