[javascript] Angular에서의 자바스크립트 DOM 조작 방법

Angular는 프론트엔드 웹 애플리케이션을 만들기 위한 강력한 프레임워크이지만 때로는 JavaScript DOM 조작이 필요할 수 있습니다. Angular는 기본적으로 데이터 바인딩을 통해 DOM 요소를 조작하지만 때로는 순수 JavaScript로 DOM 요소를 조작해야 하는 경우가 있습니다.

ElementRef 사용하기

Angular에서 순수 JavaScript DOM 조작이 필요한 경우, ElementRef를 사용할 수 있습니다. ElementRef는 Angular의 디렉티브나 컴포넌트 내에서 DOM 요소에 접근할 수 있는 방법을 제공합니다.

예를 들어, 아래와 같이 ElementRef를 이용하여 DOM 요소에 접근할 수 있습니다.

import { ElementRef } from '@angular/core';

export class MyComponent {
  constructor(private elementRef: ElementRef) {
    // ...
  }

  ngAfterViewInit() {
    // ElementRef를 사용하여 DOM 요소에 접근
    this.elementRef.nativeElement.style.backgroundColor = 'yellow';
  }
}

Renderer2 사용하기

Angular는 뷰에 대한 직접적인 접근을 피하기 위해 Renderer2를 제공합니다. Renderer2는 DOM 조작을 추상화하여 브라우저의 특정 구현 세부 사항을 숨기고 크로스 플랫폼 호환성을 제공합니다.

예를 들어, Renderer2를 사용하여 요소를 동적으로 생성하고 스타일을 설정하는 방법은 다음과 같습니다.

import { Renderer2, ElementRef, ViewChild } from '@angular/core';
 
export class MyComponent {
  @ViewChild('container', {static: true}) container: ElementRef;

  constructor(private renderer: Renderer2) {}

  ngAfterViewInit() {
    const div = this.renderer.createElement('div');
    const text = this.renderer.createText('Hello, world!');

    this.renderer.appendChild(div, text);
    this.renderer.appendChild(this.container.nativeElement, div);
    this.renderer.setStyle(div, 'color', 'blue');
  }
}

Angular에서는 Renderer2를 통해 DOM 조작을 하는 것이 권장되는 방법이며, Renderer2를 사용하면 브라우저 환경에 구애받지 않고 안전하게 DOM 조작을 할 수 있습니다.

Angular에서의 자바스크립트 DOM 조작은 주의가 필요하지만, ElementRefRenderer2를 올바르게 사용하면 안전하고 효율적으로 DOM을 조작할 수 있습니다.

참고 자료