65. Component Interaction: Input Decorator
Components form a hierarchy (parent-child). The primary way to pass data down the component tree (from Parent to Child) is using the @Input() decorator.
1. Defining the Input in the Child Component
The @Input() decorator marks a property in the child component class as available for binding by the parent's template.
typescript // product-detail.component.ts (The Child) import { Component, Input } from '@angular/core';
interface Product { name: string; price: number; }
@Component({ /* ... */ }) export class ProductDetailComponent {
// Define the property that will receive data from the parent @Input() productData: Product | undefined;
// You can also alias the input name: @Input('stockLevel') quantity: number = 0;
// Logic uses the received data get status() { return this.quantity > 0 ? 'In Stock' : 'Out of Stock'; } }
2. Passing Data from the Parent Component
The parent component uses property binding ([ ]) to set the value of the child's input properties.
typescript // parent.component.ts export class ParentComponent { selectedProduct: Product = { name: 'Widget Pro', price: 99.99 }; }
html
<app-product-detail [productData]="selectedProduct" [stockLevel]="15">
Note: Inputs must be non-private. If an object is passed via @Input, the child component should treat it as immutable (read-only). If the child mutates the object, the parent won't know unless using the OnPush change detection strategy, leading to hard-to-track bugs.