[typescript] Angular 데이터 플로우

Angular 애플리케이션에서 데이터 플로우는 중요한 개념 중 하나입니다. Angular는 컴포넌트 간의 데이터 흐름을 관리하고 어플리케이션에서 데이터 상태를 효율적으로 관리하는 방법을 제공합니다. 이 게시물에서 우리는 Angular에서 데이터 플로우를 구축하는 방법을 살펴보겠습니다.

컴포넌트 간의 데이터 플로우

Angular에서 컴포넌트 간의 데이터 플로우는 부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달하는 것으로 시작합니다. 부모 컴포넌트는 @Input 데코레이터를 사용하여 자식 컴포넌트에 데이터를 전달할 수 있습니다. 이렇게 함으로써 부모 컴포넌트에서 자식 컴포넌트로 데이터를 전달할 수 있습니다.

// 부모 컴포넌트
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <app-child [data]="parentData"></app-child>
  `
})
export class ParentComponent {
  parentData: string = 'This data is from parent component';
}

// 자식 컴포넌트
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <p>{{ data }}</p>
  `
})
export class ChildComponent {
  @Input() data: string;
}

서비스를 사용한 데이터 공유

때로는 컴포넌트 간에 직접 데이터를 전달하는 것보다 서비스를 사용하여 데이터를 공유하는 것이 유용합니다. 서비스는 Angular 애플리케이션 전반에 걸쳐 데이터를 공유하는 데 사용됩니다. 서비스를 사용하여 데이터를 저장하고 필요한 곳에서 사용할 수 있습니다.

// 데이터 서비스
import { Injectable } from '@angular/core';

@Injectable()
export class DataService {
  sharedData: string = 'This data is shared across components';
}

// 부모 컴포넌트
import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-parent',
  template: `
    <p>{{ dataService.sharedData }}</p>
  `
})
export class ParentComponent {
  constructor(private dataService: DataService) {}
}


// 자식 컴포넌트
import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-child',
  template: `
    <p>{{ dataService.sharedData }}</p>
  `
})
export class ChildComponent {
  constructor(private dataService: DataService) {}
}

컴포넌트 간 통신

때로는 부모-자식 관계를 넘어 컴포넌트 간에 통신해야 하는 경우도 있습니다. @Output 데코레이터 및 EventEmitter를 사용하여 이를 처리할 수 있습니다.

// 부모 컴포넌트
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <app-child (messageEvent)="receiveMessage($event)"></app-child>
  `
})
export class ParentComponent {
  message: string;

  receiveMessage($event) {
    this.message = $event;
  }
}

// 자식 컴포넌트
import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <button (click)="sendMessage()">Send Message</button>
  `
})
export class ChildComponent {
  @Output() messageEvent = new EventEmitter<string>();

  sendMessage() {
    this.messageEvent.emit('Message from child component');
  }
}

Angular에서 데이터 플로우를 다루기 위한 이러한 패턴들을 이용하여 애플리케이션의 데이터 상태를 효율적으로 관리할 수 있습니다. 이러한 기능들을 이용하여 Angular 애플리케이션의 데이터 플로우를 개선할 수 있습니다.

참고 자료