인턴

[ Angular ] Decorator 알아보기 / @ViewChid / @ViewChildren

Hanee_ 2022. 1. 21. 09:38

@ViewChild

@ViewChild(클래스명) 변수명: 클래스명;

뷰 쿼리를 구성하는 속성 데코레이터이다. 변경 감지기는 뷰 DOM에서 선택자와 일치하는 첫 번째 요소 또는 지시문을 찾는다. 보기 DOM이 변경되고 새 자식이 선택기와 일치하면 속성이 업데이트된다.

 

 

즉, 부모컴포넌트가 자식 컴포넌트의 상태를 변경하는 Decorator 이다.

 

 

 

다음과 같은 Selector들을 사용할 수 있다

  • @Component 또는 @Directive Decorator가 있는 모든 클래스
  • 문자열로 된 템플릿 참조 변수(예: 쿼리 <my-component #cmp></my-component> @ViewChild('cmp'))
  • 현재 구성 요소의 하위 구성 요소 트리에 정의된 공급자(예: @ViewChild(SomeService) SomeService): SomeService)
  • 문자열 토큰을 통해 정의된 모든 공급자(예: @ViewChild('some)토큰') someTokenVal: 임의)
  • TemplateRef(예: @ViewChild(TemplateRef) 템플릿을 사용한 쿼리 <ng-template>(<ng-template>)

 

 

 

사용 예제 : 스크롤 이벤트를 구현하고자 할 때,

* 탬플릿 참조변수(#)를 사용하여 자식요소의 DOM요소에 접근해 보았다.

 

[example.html]

<ion-content
        appScrollbarTheme
        #content
        [scrollEvents]='true'
        (ionScroll)= 'onScroll($event)'
>

	...
    
</ion-content>

 

[example.ts]

 export class ScrollExample {
 
  @ViewChild('content') private content: any;
  private scrollHeight: number;
  ...
 
 async scrollTo(){
    await this.content.scrollToPoint(0, this.scrollHeight, this.content.scrollDuration);
  }
 
 ...

}

 

 

 

@ViewChildren

@ViewChildren(‘설명 레이블’) children:QueryList<참조 변수의 형>;

[childrenEx.html]

<ion-content #content1 (ionScroll)='onScroll($event)'> ... </ion-content>
<ion-content #content2 (ionScroll)='onScroll($event)'> ... </ion-content>
<ion-content #content3 (ionScroll)='onScroll($event)'> ... </ion-content>

 

[childrenEx.ts]

export class ViewchildrenComponnet {
	...
  @ViewChildren('content1,content2,content3') children:QueryList<ion-content>;
  	...
}

 

 

참조 : https://skout90.github.io/2017/07/26/Angular/12.%20%EC%9E%A5%EC%8B%9D%EC%9E%90%20%EC%A0%95%EB%A6%AC-@ViewChild-@ViewChildren/