Component Communication
In a modular Angular architecture, components must act as isolated units that communicate through well-defined APIs. This ensures that your UI remains maintainable and testable. We will cover the three pillars of communication: Inputs (Data Down), Outputs (Events Up)
Step 1: The Data Model
First, we define what a "Product" looks like.
src/app/models/product.model.ts
Step 2: The Child Component (ProductDetail)
The child component is a "UI component." It doesn't fetch data; it simply displays whatever product the parent gives it.
A. The Logic (TypeScript)
We use input() to receive the product and output() to notify the parent when the user wants to add it to the cart.
src/app/product-detail/product-detail.component.ts
B. The Template (HTML)
Since product is a Signal, we read it by calling it as a function: product().
src/app/product-detail/product-detail.component.html
Step 3: The Parent Component (ProductList)
The parent component manages the list of products and knows which one is currently selected.
A. The Logic (TypeScript)
The parent imports the child component and defines a method to handle the event coming from the child.
src/app/product-list/product-list.component.ts
B. The Template (HTML)
The parent "talks" to the child through the selector <app-product-detail>.
src/app/product-list/product-list.component.html
Key Concepts Summary
input(): Creates a "hole" in the child component where the parent can plug in data.output(): Creates an "emitter" that sends signals (and data) up to the parent.$event: A reserved keyword in the parent's HTML that holds the data sent by the child viaemit().- Property Binding
[]: Always used for Inputs (Data flowing into the child). - Event Binding
(): Always used for Outputs (Events flowing out of the child).