Angular에서 ViewContainerRef 이해하기
카테고리
프로그래밍/소프트웨어 개발
서브카테고리
웹 개발
대상자
- *Angular 동적 컴포넌트 개발자**
- 중급~고급 수준의 Angular 개발자
- 동적 UI 렌더링, 모달/대시보드 구현 필요성 있는 개발자
핵심 요약
@ViewChild
와ViewContainerRef
조합을 통해 런타임에 컴포넌트를 동적으로 생성/제어 가능ViewContainerRef
는clear()
/createComponent()
/changeDetectorRef.detectChanges()
등의 핵심 메서드 제공- 사용 사례: 모달, 커스텀 UI 빌더, 플러그인 등 유연한 인터페이스 개발
섹션별 세부 요약
1. `@ViewChild`와 `ViewContainerRef`의 역할
@ViewChild('container', { read: ViewContainerRef, static: true })
- static: true
로 ngOnInit()
전에 참조를 즉시 해결
- read: ViewContainerRef
로 DOM 요소 대신 ViewContainerRef
인스턴스 획득
- 템플릿 참조 변수
#container
을 통해ng-template
영역의 컨테이너 지정
2. `ViewContainerRef`의 주요 기능
- 동적 컴포넌트 생성
```typescript
this.container.createComponent(this.component);
```
- 컴포넌트 입력값 설정
```typescript
this.componentRef.setInput('test', 42);
```
- 변경 감지 강제
```typescript
this.componentRef.changeDetectorRef.detectChanges();
```
3. 예제 코드 구조
DynamicHostComponent
클래스에서@Input()
을 통해 동적 컴포넌트 타입 및 입력값 전달ngOnChanges()
에서loadComponent()
호출하여 컨테이너 초기화 및 컴포넌트 생성MyDynamicComponent
는@Input()
test
속성을 통해 외부 데이터 바인딩
결론
ViewContainerRef
를 사용할 때는static: true
설정과clear()
호출로 메모리 누수 방지- 동적 컴포넌트 생성 후
changeDetectorRef.detectChanges()
로 변경 감지 강제 적용 @ViewChild
와ViewContainerRef
조합은 모달, 대시보드 등 유연한 UI 구현에 핵심적인 패턴