Today I Learned

[2024.10.18] Angular @Input()과 @Output() 이해하기

monkeykim 2024. 10. 18. 00:05

Angular를 사용하다 보면 부모 컴포넌트와 자식 컴포넌트 간의 데이터 통신이 필수적이다. 이때 중요한 두 가지 데코레이터가 바로 @Input()과 @Output()이다. 이 글에서 각각의 역할과 사용법을 예시를 통해 쉽게 설명하려고 한다.


@Input() – 부모에서 자식으로 데이터 전달

@Input()은 부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달할 때 사용한다. 예를 들어, 부모 컴포넌트에서 자식 컴포넌트에 텍스트 메시지나 객체와 같은 데이터를 보내고 싶을 때 유용하다.

@Input() 사용 예시

1. 부모 컴포넌트 (ParentComponent)

부모 컴포넌트에서 자식 컴포넌트에 메시지를 전달하고자 한다.

<!-- parent.component.html -->
<h1>부모 컴포넌트</h1>
<app-child [message]="parentMessage"></app-child>
// parent.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
})
export class ParentComponent {
  parentMessage = '안녕하세요! 부모에서 보낸 메시지입니다.';
}

이 코드를 보면 parentMessage라는 변수를 <app-child> 자식 컴포넌트로 전달하고 있다. 이때 @Input() 데코레이터를 사용하면, 자식 컴포넌트에서 이 데이터를 받을 수 있다.

 

2. 자식 컴포넌트 (ChildComponent)

이제 자식 컴포넌트에서 @Input()으로 부모의 데이터를 받아서 사용할 수 있다.

<!-- child.component.html -->
<h2>자식 컴포넌트</h2>
<p>부모로부터 받은 메시지: {{ message }}</p>
// child.component.ts
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
})
export class ChildComponent {
  @Input() message: string;  // 부모로부터 전달받은 데이터
}

이렇게 하면 자식 컴포넌트에서 부모 컴포넌트로부터 전달된 message를 받아서 화면에 표시할 수 있다.


@Output() – 자식에서 부모로 이벤트 전달

반대로 @Output()은 자식 컴포넌트에서 부모 컴포넌트로 이벤트를 전달할 때 사용된다. 자식 컴포넌트에서 어떤 동작이 발생했을 때, 이를 부모 컴포넌트에 알려주기 위한 방법이다. @Output()은 일반적으로 EventEmitter와 함께 사용된다.

@Output() 사용 예시

1. 자식 컴포넌트 (ChildComponent)

자식 컴포넌트는 버튼을 클릭할 때 부모에게 메시지를 전달하도록 설정한다.

<!-- child.component.html -->
<h2>자식 컴포넌트</h2>
<button (click)="sendMessage()">부모에게 메시지 보내기</button>
// 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>();

  sendMessage() {
    this.messageEvent.emit('자식 컴포넌트에서 보낸 메시지입니다!');
  }
}

@Output()과 EventEmitter를 사용하여 부모 컴포넌트로 "이벤트 발생"을 알리고, 해당 메시지를 전달한다.

 

2. 부모 컴포넌트 (ParentComponent)

부모 컴포넌트는 자식 컴포넌트에서 발생한 이벤트를 수신하고, 전달된 메시지를 화면에 표시한다.

<!-- parent.component.html -->
<h1>부모 컴포넌트</h1>
<app-child (messageEvent)="receiveMessage($event)"></app-child>
<p>자식으로부터 받은 메시지: {{ receivedMessage }}</p>
// parent.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
})
export class ParentComponent {
  receivedMessage: string;

  receiveMessage(event: string) {
    this.receivedMessage = event;  // 자식 컴포넌트로부터 메시지 받기
  }
}

이렇게 하면 자식 컴포넌트에서 버튼을 클릭할 때마다 부모 컴포넌트가 그 메시지를 받아 화면에 표시할 수 있다.


정리

  • @Input(): 부모 컴포넌트가 자식 컴포넌트로 데이터를 전달할 때 사용한다. 자식 컴포넌트는 @Input()을 통해 부모로부터 데이터를 받아서 처리할 수 있다.
  • @Output(): 자식 컴포넌트가 부모 컴포넌트로 이벤트를 전달할 때 사용한다. 자식 컴포넌트에서 발생한 이벤트는 @Output()과 EventEmitter를 통해 부모 컴포넌트에 전달된다.