Angular 컴포넌트 통신(@Input, @Output)
Angular에서의 컴포넌트 통신은 애플리케이션 내의 다양한 컴포넌트 간에 데이터와 이벤트를 효과적으로 전달하는 방법입니다.
Angular 애플리케이션은 여러 개의 컴포넌트로 구성되어 있으며, 각 컴포넌트는 서로 독립적으로 동작합니다.
그러나 컴포넌트 간의 데이터나 이벤트 전달이 필요할 때가 많습니다.
이를 위해 Angular는 주로 @Input과 @Output 데코레이터를 제공합니다.
- 데이터 바인딩: 부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달하는 방법입니다. 이는 @Input 데코레이터를 사용하여 이루어집니다.
- 이벤트 전달: 자식 컴포넌트가 부모 컴포넌트에 이벤트를 전달할 때 사용하는 방법입니다. 이는 @Output 데코레이터를 통해 수행됩니다.
@Input 데코레이터
@Input 데코레이터는 부모 컴포넌트가 자식 컴포넌트로 데이터를 전달할 수 있도록 하는 역할을 합니다.
이 데코레이터가 붙은 속성은 부모 컴포넌트의 템플릿에서 바인딩할 수 있으며, 해당 속성의 값이 변경되면 자식 컴포넌트에서도 자동으로 업데이트됩니다.
@Input 예시
부모 컴포넌트 (ParentComponent)
- HTML (템플릿)
<!-- parent.component.html -->
<h2>Parent Component</h2>
<app-child [childData]="parentData"></app-child>
- TypeScript
// parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
})
export class ParentComponent {
parentData: string = 'Hello from Parent!';
}
자식 컴포넌트 (ChildComponent)
- HTML (템플릿)
<!-- child.component.html -->
<h3>Child Component</h3>
<p>Received from parent: {{ childData }}</p>
- TypeScript
// child.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
})
export class ChildComponent {
@Input() childData!: string;
}
@Output 데코레이터
@Output 데코레이터는 자식 컴포넌트가 부모 컴포넌트에 이벤트를 전달할 수 있도록 하는 역할을 합니다.
자식 컴포넌트에서 발생한 이벤트를 부모 컴포넌트가 수신할 수 있도록 합니다.
일반적으로 EventEmitter와 함께 사용되어, 자식 컴포넌트에서 이벤트가 발생할 때 부모 컴포넌트에 알릴 수 있습니다.
@Output 예시
자식 컴포넌트 (ChildComponent)
- HTML (템플릿)
<!-- child.component.html -->
<h3>Child Component</h3>
<button (click)="sendToParent()">Send Data to Parent</button>
- TypeScript
// child.component.ts
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter<string>();
sendToParent() {
this.messageEvent.emit('Hello from Child!');
}
}
부모 컴포넌트 (ParentComponent)
- HTML (템플릿)
<!-- parent.component.html -->
<h2>Parent Component</h2>
<app-child (messageEvent)="receiveFromChild($event)"></app-child>
<p>Message from child: {{ childMessage }}</p>
- TypeScript
// parent.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
})
export class ParentComponent {
childMessage: string = '';
receiveFromChild(message: string) {
this.childMessage = message;
}
}
예시 > 장바구니 컴포넌트 (부모 컴포넌트) , 상품 컴포넌트 (자식 컴포넌트)
부모 컴포넌트가 "장바구니" 역할을 하고, 자식 컴포넌트가 "상품" 역할을 하도록 하여 장바구니에 상품을 추가하는 예제를 만들어 보겠습니다.
이 예제는 @Input을 사용해 부모 컴포넌트가 자식 컴포넌트로 상품 정보를 전달하고, @Output을 사용해 자식 컴포넌트에서 부모 컴포넌트로 상품을 추가하는 이벤트를 전달하는 방식으로 구성됩니다.
1. 장바구니 컴포넌트 (부모 컴포넌트)
- 사용자가 선택한 상품들이 이곳에 저장되고, 자식 컴포넌트로부터 상품을 추가하라는 이벤트를 받습니다.
HTML (템플릿)
<!-- cart.component.html -->
<h2>Shopping Cart</h2>
<ul>
<li *ngFor="let item of cartItems">{{ item }}</li>
</ul>
<!-- 상품 컴포넌트를 여러 개 추가하여, 각 상품마다 'Add to Cart' 버튼이 있음 -->
<app-product
*ngFor="let product of products"
[productName]="product"
(addProductEvent)="addToCart($event)"
></app-product>
TypeScript
// cart.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
})
export class CartComponent {
// 장바구니에 담긴 상품 목록
cartItems: string[] = [];
// 장바구니에 추가할 수 있는 상품 목록
products: string[] = ['Laptop', 'Smartphone', 'Headphones', 'Keyboard'];
// 상품을 장바구니에 추가하는 메서드
addToCart(product: string) {
this.cartItems.push(product);
}
}
2. 상품 컴포넌트 (자식 컴포넌트)
- 각 상품마다 'Add to Cart' 버튼을 제공하고, 클릭 시 부모 컴포넌트에 상품 추가 요청을 보냅니다.
HTML (템플릿)
<!-- product.component.html -->
<div class="product">
<h3>{{ productName }}</h3>
<button (click)="addProductToCart()">Add to Cart</button>
</div>
TypeScript
// product.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
})
export class ProductComponent {
// 부모 컴포넌트로부터 받는 상품명 데이터
@Input() productName!: string;
// 부모 컴포넌트로 상품 추가 요청을 보내는 이벤트
@Output() addProductEvent = new EventEmitter<string>();
// 'Add to Cart' 버튼 클릭 시 이벤트 발생
addProductToCart() {
this.addProductEvent.emit(this.productName);
}
}
- 부모 컴포넌트(CartComponent)는 products 배열을 통해 다양한 상품을 자식 컴포넌트인 ProductComponent로 전달합니다.
- 각 ProductComponent는 @Input을 통해 받은 상품 이름을 표시하고, 'Add to Cart' 버튼을 제공합니다.
- 버튼 클릭 시 ProductComponent는 @Output을 통해 부모 컴포넌트로 상품 이름을 전달합니다.
- 부모 컴포넌트는 전달받은 상품 이름을 cartItems 배열에 추가하여 장바구니 목록을 업데이트합니다.
'개발 공부 > Angular' 카테고리의 다른 글
| BehaviorSubject를 활용한 View 상태 관리 (0) | 2024.11.17 |
|---|---|
| Angular / Ionic Router Outlet (0) | 2024.11.07 |
| Angular LifeCycle (1) | 2024.11.02 |
| Angular Standalone (2) | 2024.10.27 |
| Angular 란 (0) | 2024.07.21 |