본문 바로가기

개발 공부/Angular

Angular LifeCycle

Angular 컴포넌트 생명주기란?

Angular 컴포넌트 생명주기는 컴포넌트가 생성, 렌더링, 변경 감지, 파괴되는 일련의 과정을 말합니다. 각 단계에서 특정 함수가 호출되어 코드가 실행되는데, 이 함수들을 생명주기 훅(lifecycle hook)이라고 부릅니다.

 

생명주기 훅을 통해 개발자는 컴포넌트가 언제 초기화되는지, 언제 상태 변화가 발생하는지, 그리고 언제 컴포넌트가 파괴되는지 알 수 있고, 필요한 작업을 실행할 수 있습니다.

컴포넌트 생명주기 주요 단계

  1. 생성 단계: 컴포넌트가 인스턴스화되고, Angular가 생성자와 함께 필요한 의존성을 주입합니다.
  2. 초기화 단계: Angular는 입력 속성을 설정하고 ngOnInit 같은 초기화 관련 훅을 호출합니다.
  3. 변경 감지 및 업데이트 단계: Angular는 컴포넌트 상태나 입력값이 변경될 때마다 변경 사항을 감지하고 필요 시 다시 렌더링을 수행합니다. 이때 ngOnChanges와 ngDoCheck 같은 훅이 호출될 수 있습니다.
  4. 파괴 단계: 컴포넌트가 더 이상 필요하지 않으면 메모리 누수를 방지하기 위해 제거되며, 이때 ngOnDestroy 훅을 호출해 리소스를 정리할 수 있습니다.

Angular 생명주기 훅 개요

  • ngOnChanges: @Input으로 전달된 값이 변경될 때마다 호출됩니다.
  • ngOnInit: 컴포넌트가 초기화될 때 한 번 호출되며, 데이터 초기화나 API 호출에 주로 사용됩니다.
  • ngDoCheck: Angular의 기본 변경 감지 이외의 추가 변경 사항을 확인할 때 호출됩니다.
  • ngAfterContentInit: 콘텐츠가 컴포넌트에 삽입된 후에 한 번 호출됩니다.
  • ngAfterContentChecked: 콘텐츠 삽입 후에 변경 사항이 감지될 때마다 호출됩니다.
  • ngAfterViewInit: 컴포넌트의 뷰 및 자식 뷰가 초기화된 후에 한 번 호출됩니다.
  • ngAfterViewChecked: 뷰 초기화 후, 변경 사항이 감지될 때마다 호출됩니다.
  • ngOnDestroy: 컴포넌트가 소멸되기 직전에 호출되어 리소스를 해제할 때 주로 사용됩니다.

 

1. ngOnChanges

ngOnChanges 훅은 @Input을 통해 부모 컴포넌트에서 전달된 값이 변경될 때마다 호출됩니다.

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `<p>현재 값: {{ value }}</p>`
})
export class ChildComponent implements OnChanges {
  @Input() value: string = '';

  ngOnChanges(changes: SimpleChanges) {
    console.log('변경된 값:', changes.value.currentValue);
  }
}

 

부모 컴포넌트가 value 값을 변경할 때마다 ngOnChanges 훅이 호출되어 변경된 값을 로그로 출력합니다.

 

2. ngOnInit

ngOnInit 훅은 컴포넌트가 처음 생성되고 초기화될 때 한 번 호출됩니다. 주로 데이터를 초기화하거나 API를 호출하는 데 사용됩니다.

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

@Component({
  selector: 'app-example',
  template: `<p>초기 데이터: {{ data }}</p>`
})
export class ExampleComponent implements OnInit {
  data: string = '';

  ngOnInit() {
    this.data = '초기 데이터 로드 완료';
    console.log('ngOnInit 실행');
  }
}

 

ngOnInit에서 데이터를 초기화하고, data 속성에 기본값을 설정했습니다.

 

3. ngDoCheck

ngDoCheck 훅은 Angular의 기본 변경 감지 이외의 추가적인 변경 사항을 수동으로 감지할 때 사용합니다.

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

@Component({
  selector: 'app-check',
  template: `<p>변경 감지 상태</p>`
})
export class CheckComponent implements DoCheck {
  ngDoCheck() {
    console.log('변경 감지 발생');
  }
}

 

 

4. ngAfterContentInit 및 ngAfterContentChecked

이 훅은 컴포넌트 콘텐츠가 초기화되고 변경될 때 호출됩니다. 주로 ng-content에 삽입된 내용이 제대로 표시되었는지 확인하는 데 사용됩니다.

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

@Component({
  selector: 'app-parent',
  template: `<ng-content></ng-content>`
})
export class ParentComponent implements AfterContentInit {
  @ContentChild('childContent') content: any;

  ngAfterContentInit() {
    console.log('콘텐츠 초기화:', this.content);
  }
}

 

5. ngAfterViewInit 및 ngAfterViewChecked

ngAfterViewInit은 컴포넌트의 뷰가 초기화된 후에 호출되며, 주로 자식 컴포넌트와 관련된 초기화 작업에 사용됩니다.

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

@Component({
  selector: 'app-parent-view',
  template: `<app-child #child></app-child>`
})
export class ParentViewComponent implements AfterViewInit {
  @ViewChild('child') childComponent: any;

  ngAfterViewInit() {
    console.log('자식 뷰 초기화 완료:', this.childComponent);
  }
}

 

6. ngOnDestroy

ngOnDestroy 훅은 컴포넌트가 소멸되기 직전에 호출되며, 구독 해제나 타이머 정리 등 리소스를 해제하는 작업에 사용됩니다.

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

@Component({
  selector: 'app-destroy',
  template: `<p>앱 종료 전 정리</p>`
})
export class DestroyComponent implements OnDestroy {
  ngOnDestroy() {
    console.log('ngOnDestroy 호출');
  }
}

 

 

 

'개발 공부 > Angular' 카테고리의 다른 글

Angular / Ionic Router Outlet  (0) 2024.11.07
Angular 컴포넌트 통신(@Input, @Output)  (2) 2024.11.05
Angular Standalone  (2) 2024.10.27
Angular 란  (0) 2024.07.21
Angular / @ngrx / store  (0) 2024.07.19