@Input() and @Output() are decorators for communication between a parent component and a child component. @Input() — parent to child Lets the parent pass data into the child through property binding. // child: product-card.component.ts @Input({ required: true }) product!: Product; <!-- parent template --> <app-product-card [product]="selectedProduct"></app-product-card> Options include required: true, alias, and transform (for example booleanAttribute to convert string attributes). @Output() — child to parent Lets the child emit events that the parent listens to, using an EventEmitter. // child @Output() addToCart = new EventEmitter<Product>(); onAdd() { this.addToCart.emit(this.product); } <!-- parent --> <app-product-card [product]="p" (addToCart)="cart.add($event)"></app-product-card> $event contains the emitted value. Two-way binding Combine an input and an output named xChange to support [(x)]: @Input() value = 0; @Output() valueChange = new EventEmitter<number>(); Usage: <app-counter [(value)]="count"></app-counter> Signal-based alternatives (Angular 17.1+) Modern Angular offers function-based APIs that work well with signals: product = input.required<Product>(); // read as this.product() addToCart = output<Product>(); // this.addToCart.emit(p) value = model(0); // two-way binding with [(value)] Best practices - Keep child components presentational: data in via inputs, events out via outputs, no direct service calls when not necessary. - Treat inputs as immutable; create new objects instead of mutating, which also works best with OnPush change detection. - React to input changes with ngOnChanges, setters, or computed() and effect() for signal inputs. - For communication between components that are not parent and child, use a shared service instead of long chains of inputs and outputs.
Ravindra Wadile · · 0 likes