[angular] @viewchild를 사용하여 여러 viewchildren에 액세스

예를 들어 for 루프에 배치 한 사용자 지정 구성 요소를 만들었습니다.

<div *ngFor="let view of views">

     <customcomponent></customcomponent>

</div>

출력은 다음과 같습니다.

<customcomponent></customcomponent>
<customcomponent></customcomponent>
<customcomponent></customcomponent>

이러한 구성 요소의 수가 다를 수있을 때 @viewchild 구문 또는 다른 수단을 사용하여 이러한 구성 요소에 대한 참조를 얻는 방법을 알고 싶습니다.

구성 요소에 이름을 지정할 수있는 경우 예 :

<customcomponent #compID></customcomponent>

그런 다음 다음과 같이 참조 할 수 있습니다.

@ViewChild('compID') test: CustomComponent

인덱스를 사용하는 것과 같은 경우가 아닐 때 어떻게 참조합니까?

(이 질문은 아래 나열된 답변에서 볼 수 있듯이 이전에 질문 한 다른 질문에 따라 ElementRef를 사용하는 것과 관련이 없습니다.)이 질문은 여러 @ViewChild 액세스 및 목록 쿼리 사용과 관련이 있습니다.



답변

@ViewChildrenfrom @angular/core을 사용 하여 구성 요소에 대한 참조를 가져옵니다.

주형

<div *ngFor="let v of views">
    <customcomponent #cmp></customcomponent>
</div>

구성 요소

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

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

l̶i̶v̶e̶ ̶d̶e̶m̶o̶


답변

QueryList와 결합 된 @ViewChildren 데코레이터를 사용하십시오. 둘 다 “@ angular / core”에서 가져온 것입니다.

@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;

각 어린이와 함께 무언가를하는 것은 다음과 같습니다.
this.customComponentChildren.forEach((child) => { child.stuff = 'y' })

angular.io에 추가 문서가 있습니다. 특히
https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild


답변