Angular @ViewChildren QueryList

agnusdei·2023년 7월 7일
0

Angular에서 ViewChildren 데코레이터는 자식 요소들을 선택하는 데 사용됩니다. ViewChildren@ViewChild와 유사하지만, 단일 자식 요소 대신 여러 자식 요소를 선택할 수 있습니다.

다음은 ViewChildren를 사용한 코드 예시입니다. 이 예시에서는 자식 요소 중에서 ChildComponent를 찾아 각각의 인스턴스를 가져옵니다.

import { Component, ViewChildren, QueryList } from '@angular/core';
import { ChildComponent } from './child.component';

@Component({
  selector: 'parent-component',
  template: `
    <div>
      <child-component></child-component>
      <child-component></child-component>
      <child-component></child-component>
    </div>
  `,
})
export class ParentComponent {
  @ViewChildren(ChildComponent) children: QueryList<ChildComponent>;

  ngAfterViewInit() {
    // 자식 요소들이 초기화된 후 실행됩니다.
    this.children.forEach(child => {
      // 자식 요소들과 상호작용하는 로직을 작성합니다.
      // 예: child.doSomething();
    });
  }
}

위의 예시에서 ParentComponentChildComponent를 세 번 사용하고 있습니다. @ViewChildren(ChildComponent) 데코레이터는 ChildComponent를 찾아 해당하는 모든 인스턴스를 QueryList 객체인 children에 할당합니다.

ngAfterViewInit() 메서드는 ParentComponent의 뷰와 자식 요소들이 초기화된 후에 실행됩니다. 이 메서드에서 children 객체에 대해 forEach 루프를 돌며 자식 요소들과 상호작용하는 로직을 작성할 수 있습니다.

ViewChildren를 사용할 때 주의해야 할 점은 자식 요소들이 초기화된 후에만 접근할 수 있다는 것입니다. 그러므로 ngAfterViewInit() 또는 그 이후의 라이프사이클 후킹 함수에서 ViewChildren를 사용해야 합니다.

ViewChildren는 자식 요소들 중에서 특정 조건을 만족하는 요소들을 선택하기 위해 선택자를 추가로 사용할 수도 있습니다. 선택자는 자식 요소의 클래스, 디렉티브, 템플릿 참조 변수 등을 기준으로 지정할 수 있습니다.

이렇게 ViewChildren를 사용하여 부모 컴포넌트에서 자식 요소들을 선택하고 상호작용할 수 있습니다.

0개의 댓글