Angular @ViewChildren 설명 및 예시
@ViewChild(Index1Section, { read: ElementRef, static: true })
section1!: ElementRef;
`@ViewChild(SubSection1Section, { read: ElementRef, static: true }) section1!: ElementRef;` 코드는 Angular 프레임워크에서 `@ViewChild` 데코레이터를 사용하여 컴포넌트 클래스에서 자식 요소를 참조하는 방법을 나타냅니다.
`@ViewChild` 데코레이터는 Angular에서 자식 요소에 대한 참조를 얻을 때 사용됩니다. 이를 통해 부모 컴포넌트는 자식 컴포넌트의 속성이나 메서드에 직접적으로 접근할 수 있습니다. `@ViewChild` 데코레이터는 다음과 같은 구문을 가지고 있습니다:
@ViewChild(selector, { options }) propertyName: ElementRef;
- `selector`는 자식 요소를 선택하기 위한 쿼리 선택자입니다. 쿼리 선택자는 자식 요소를 찾기 위해 CSS 선택자나 컴포넌트 클래스를 사용할 수 있습니다.
- `{ options }`는 선택적인 구성 옵션입니다. `read` 옵션을 사용하여 참조된 요소의 타입을 지정할 수 있습니다.
- `propertyName`은 부모 컴포넌트에서 자식 요소에 대한 참조를 할당할 속성의 이름입니다.
- `ElementRef`는 Angular에서 제공하는 클래스로, DOM 요소에 대한 참조를 나타냅니다.
따라서, `@ViewChild(SubSection1Section, { read: ElementRef, static: true }) section1!: ElementRef;` 코드는 부모 컴포넌트에서 `SubSection1Section`이라는 자식 컴포넌트의 요소에 대한 참조를 얻기 위해 사용됩니다. `ElementRef`를 사용하여 DOM 요소에 직접 접근할 수 있게 됩니다.
예를 들어, 자식 컴포넌트에서 특정 DOM 요소의 스타일을 변경하거나 이벤트를 처리해야 할 경우, `@ViewChild`를 사용하여 해당 요소에 대한 참조를 얻고, `ElementRef`를 통해 요소에 접근하여 원하는 작업을 수행할 수 있습니다.
import {
ViewChildren,
QueryList,
} from '@angular/core';
@ViewChildren(SideMenuItemComponent)
menuItems!: QueryList<SideMenuItemComponent>;
handleSidemenuItemClick(route: Route) {
this.menuItems.map((item) => (item.isOpen = false)); // map
const toBeOpened = this.menuItems.find((item) => item.route === route);
if (toBeOpened) {
toBeOpened.isOpen = true;
}
}
1. 메뉴 컴포넌트에서 메뉴카드 컴포넌트 자식 요소를 다루는 예시