본문 바로가기

개발 공부/Angular

@ViewChild와 @ViewChildren (3) ngAfterViewInit, static

ngAfterViewInit 활용

ngAfterViewInit

Angular의 라이프사이클 훅 중 하나인 ngAfterViewInit는 뷰 초기화가 완료된 후 호출됩니다.

이 훅을 사용하면 @ViewChild@ViewChildren을 통해 참조한 DOM 요소나 자식 컴포넌트가 완전히 생성된 이후에 접근할 수 있습니다.

ngAfterViewInit에서 ViewChild 활용하기

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

@Component({
  selector: 'app-example',
  template: `<p #textElement>이 문장은 ngAfterViewInit에서 변경됩니다.</p>`
})
export class ExampleComponent implements AfterViewInit {
  @ViewChild('textElement') textElement!: ElementRef;

  ngAfterViewInit() {
    this.textElement.nativeElement.textContent = 'ngAfterViewInit에서 변경된 문장';
  }
}
  • @ViewChild를 사용하여 <p> 요소를 참조합니다.
  • ngAfterViewInit에서 해당 요소의 내용을 변경할 수 있습니다.

 


 

@ViewChild의 static 옵션

static: true vs static: false 차이

Angular 8부터 @ViewChild@ViewChildrenstatic 옵션이 추가되었습니다.

이 옵션은 컴포넌트 초기화 시점에서 뷰 요소를 언제 접근할지를 결정합니다.

static: true ngOnInit에서 접근 가능 (뷰가 렌더링되기 전)
static: false ngAfterViewInit에서 접근 가능 (뷰가 렌더링된 후)

 static 옵션 비교

@ViewChild('textElement', { static: true }) textElement1!: ElementRef;
@ViewChild('textElement', { static: false }) textElement2!: ElementRef;
  • static: true일 경우 ngOnInit에서 textElement1에 접근할 수 있습니다.
  • static: false일 경우 ngAfterViewInit에서 textElement2에 접근해야 합니다.

일반적으로 static: false를 사용하는 것이 권장됩니다.

 

동적 요소 접근하기

@ViewChildren과 QueryList 활용

@ViewChildren을 활용하면 여러 개의 동적 요소를 한 번에 제어할 수 있습니다.

import { Component, ViewChildren, QueryList, AfterViewInit, ElementRef } from '@angular/core';

@Component({
  selector: 'app-dynamic-elements',
  template: `
    <p #paragraph *ngFor="let text of texts">{{ text }}</p>
    <button (click)="updateText()">텍스트 변경</button>
  `
})
export class DynamicElementsComponent implements AfterViewInit {
  @ViewChildren('paragraph') paragraphs!: QueryList<ElementRef>;
  texts = ['첫 번째 문장', '두 번째 문장', '세 번째 문장'];

  ngAfterViewInit() {
    this.paragraphs.forEach((p, index) => {
      console.log(`문장 ${index + 1}:`, p.nativeElement.textContent);
    });
  }

  updateText() {
    this.paragraphs.forEach((p, index) => {
      p.nativeElement.textContent = `변경된 문장 ${index + 1}`;
    });
  }
}

 

  • *ngFor을 사용하여 여러 개의 <p> 요소를 동적으로 생성합니다.
  • @ViewChildren을 활용하여 모든 <p> 요소를 QueryList로 참조할 수 있습니다.
  • updateText()를 호출하면 모든 문장의 내용을 한 번에 변경할 수 있습니다.

 


동적으로 추가된 요소 접근하기

setTimeout을 활용한 동적 요소 추가 및 접근

Angular에서 동적으로 추가된 요소는 기본적으로 @ViewChild@ViewChildren으로 바로 탐색되지 않습니다.

따라서 setTimeout()이나 ChangeDetectorRef.detectChanges()를 사용하여 변화를 감지해야 합니다.

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

@Component({
  selector: 'app-dynamic-viewchild',
  template: `
    <button (click)="addElement()">요소 추가</button>
    <div #container></div>
  `,
})
export class DynamicViewChildComponent implements AfterViewInit {
  @ViewChild('container') container!: ElementRef;

  ngAfterViewInit() {
    console.log('초기 컨테이너:', this.container.nativeElement.innerHTML);
  }

  addElement() {
    setTimeout(() => {
      this.container.nativeElement.innerHTML += '<p>새로운 문장</p>';
    });
  }
}

 

  • @ViewChild는 처음 렌더링된 요소만 참조합니다.
  • setTimeout()을 사용하여 요소를 동적으로 추가하면 Angular의 변경 감지 없이도 DOM이 업데이트됩니다.

 

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

Angular CanActivate  (0) 2025.03.13
@ContentChild와 @ContentChildren 활용  (0) 2025.02.21
@ViewChild와 @ViewChildren (2) 기본 활용  (0) 2025.02.15
@ViewChild와 @ViewChildren (1)  (0) 2025.02.13
RxJS의 ReplaySubject 2 / Angular  (0) 2024.12.15