Angular에서 부모 컴포넌트로 데이터 전달하기

자식 컴포넌트에서 부모 컴포넌트로 데이터를 전달할 수 있습니다. 이는 특수 객체 EventEmitter와 메서드 emit를 사용하여 이벤트를 발생시킴으로써 수행됩니다. 자식 컴포넌트는 이벤트와 함께 일부 데이터를 전달하여 이벤트를 발생시키고, 부모 컴포넌트는 이벤트를 캐치하여 자식 컴포넌트로부터 데이터를 받습니다.

실제로 시도해 봅시다. 이를 위해 몇 가지 단계를 거쳐야 합니다. 먼저 자식 컴포넌트에 데코레이터 @Output와 클래스 EventEmitter를 임포트합니다:

app/user/user.component.tsimport { Component, Output, EventEmitter } from '@angular/core';

이제 자식 클래스에 속성 onData를 만들고, 그 값으로 문자열을 포함하는 새로운 객체 EventEmitter를 설정합니다:

app/user/user.component.tsexport class UserComponent {
  @Output()
  public onData = new EventEmitter<string>();
}

이제 메서드 send를 만들어, 호출 시 지정된 텍스트와 함께 onData 이벤트를 부모 컴포넌트로 발생시킵니다:

app/user/user.component.tsexport class UserComponent {
  @Output()
  public onData = new EventEmitter<string>();
  
  send() {
    this.onData.emit('xxx');
  }
}

자식 컴포넌트의 템플릿에 버튼을 만들고, 클릭 시 메서드 send가 호출되도록 합니다:

app/user/user.component.html<button (click)="send()">
  데이터 전송
</button>

부모 컴포넌트에 메서드 onData를 만들고, 자식 컴포넌트에서 해당 이벤트가 발생하면 자동으로 호출되도록 합니다. 메서드의 매개변수에는 전달된 데이터가 들어갑니다:

app/app.component.tsexport class AppComponent {
  public onData(data: string) {
    console.log(data);
  }
}

부모 컴포넌트의 템플릿에서 자식 컴포넌트 태그에 이벤트를 바인딩합니다:

app/app.component.html<app-user (onData)="onData($event)"></app-user>
Задание 1

자식 컴포넌트에서 서로 다른 이벤트를 발생시키는 세 개의 버튼을 만드세요. 부모 컴포넌트에서 발생된 이벤트를 캐치하세요.