본문 바로가기
Frontend/Angular

[Angular] 07. Custom events with outputs

by jyc_ 2025. 2. 1.
 Angular 공식 문서를 실습하고 정리하는 글입니다.

 

Output

  • 자식 컴포넌트가 부모 컴포넌트로 데이터나 이벤트를 전달하는 방법
  • 자식 컴포넌트에서 동작이 발생했을 때(버튼 클릭, 폼 제출 등), 그 사실을 부모 컴포넌트에 알려야 할 때 사용한다.

 

출력 사용 예제

자식 컴포넌트에서 출력 정의

import { Component, output } from '@angular/core';

@Component({
  selector: 'app-expandable-panel',
  template: `<button (click)="closePanel()">Close Panel</button>`
})
export class ExpandablePanel {
  // 출력 정의: panelClosed라는 이벤트를 생성
  panelClosed = output<void>();

  closePanel() {
    // 이벤트 발생
    this.panelClosed.emit();
  }
}

 

부모 컴포넌트에서 출력 사용

<!-- 자식 컴포넌트에서 panelClosed 이벤트가 발생하면 부모 onPanelClosed() 호출 -->
<app-expandable-panel (panelClosed)="onPanelClosed()"></app-expandable-panel>
export class ParentComponent {
  onPanelClosed() {
    console.log('Panel was closed!');
  }
}

 

이벤트 데이터 전달

자식 컴포넌트

import { Component, output } from '@angular/core';

@Component({
  selector: 'app-custom-slider',
  template: `<input type="range" (input)="onInput($event)">`
})
export class CustomSlider {
  // 출력 정의: valueChanged라는 이벤트를 생성
  valueChanged = output<number>();

  onInput(event: Event) {
    const value = (event.target as HTMLInputElement).valueAsNumber;
    // 이벤트와 함께 데이터 전달
    this.valueChanged.emit(value);
  }
}

 

부모 컴포넌트

<app-custom-slider (valueChanged)="onValueChanged($event)"></app-custom-slider>
export class ParentComponent {
  onValueChanged(value: number) {
    console.log('Slider value:', value);
  }
}
  1. 자식 컴포넌트에서 valueChanged 이벤트 발생
  2. 부모 컴포넌트의 onValueChanged() 호출
  3. $event 를 통해 데이터를 받음

 

'Frontend > Angular' 카테고리의 다른 글

[Angular] 06. Components: Input Properties  (0) 2025.01.31
[Angular] 05. Components: Selectors  (1) 2025.01.31
[Angular] 04. Dependency Injection  (0) 2025.01.31
[Angular] 03. Dynamic interface with templates  (0) 2025.01.31
[Angular] 02. Signal  (0) 2025.01.31