ngZoneEventCoalescing으로 이벤트 버블링 해결

Adam Kim·2025년 10월 7일

angular

목록 보기
42/102

원인

js에는 부모와 자식간 이벤트 버블링이 발생하는데 대부분의 경우 이벤트 버블링 때문에 불 필요한 이벤트를 처리하는 등의 문제를 겪습니다.

Angular에서도 역시 이벤트 버블링이 발생하는데 이는 랜더링 성능에 영향을 끼치게 됩니다.



이를 해결하기 위해 changeDetection을 설정하는데 9버전 이하에서는 changeDetection을 설정하여도 ngAfterViewInit에서 타이밍 이슈로 인해 setTimeout에 함수를 담아야 실행 되는 경우가 있었습니다.

ngAfterViewInit(){  
    setTimeout(()=> {
        this.changeStatus()
    })  
}

Angular 9 버전부터 보다 근본적인 버블링 해결책을 구현하였으며, 또한 위의 setTimeout 코드는 changeDetection의 detectChange으로 이벤트를 문제없이 적용할 수 있습니다.

ngAfterViewInit(){  
    this.changeStatus();
    this.cdr.detectChanges();  
}

해결

main.ts에서 Angular Module boostrap 설정 시 옵션을 추가합니다.

   platformBrowserDynamic()
  .bootstrapModule(AppModule, { ngZoneEventCoalescing: true })

추가: 최신 Angular (v17+)에서의 해결책

Angular 17부터는 NgModule 없이 독립형(Standalone) API를 사용하는 것이 기본입니다.

main.ts에서 platformBrowserDynamic().bootstrapModule()을 호출하는 대신 bootstrapApplication() 함수를 사용하며, 애플리케이션의 전역 설정은 app.config.ts 파일에서 관리됩니다.

ngZoneEventCoalescing 설정은 NgZone의 구성 옵션이므로, provideZoneChangeDetection이라는 프로바이더 함수를 통해 설정합니다.

해결책 (독립형 API 기반 - Angular 17+ 등)

app.config.ts 파일의 providers 배열에 provideZoneChangeDetection를 추가하고, 옵션 객체에 eventCoalescing: true를 전달합니다.

// src/app/app.config.ts

import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),

    // 1. Zone.js 관련 설정을 위한 프로바이더 함수 호출
    // 2. 옵션 객체를 통해 이벤트 병합(coalescing) 활성화
    provideZoneChangeDetection({ eventCoalescing: true })
  ]
};

이 appConfig는 main.ts에서 bootstrapApplication 함수에 전달되어 애플리케이션 전체에 적용됩니다.

// src/main.ts (참고용)

import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';

bootstrapApplication(AppComponent, appConfig)
  .catch((err) => console.error(err));

참고 사이트

profile
Angular2+ Developer

0개의 댓글