@viewchild [duplicate]를 사용하여 여러 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 액세스 및 목록 쿼리 사용과 관련이 있습니다.
@ViewChildren
from @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());
}
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에 추가 문서가 있습니다.
참고 URL : https://stackoverflow.com/questions/40165294/access-multiple-viewchildren-using-viewchild
'IT story' 카테고리의 다른 글
Android Studio는 내 .apk 파일을 어디에 구축합니까? (0) | 2020.09.04 |
---|---|
Twitter 부트 스트랩을 사용하여 자동으로 경고를 닫는 방법 (0) | 2020.09.04 |
Java에서 다른 반환 유형으로 오버로드? (0) | 2020.09.04 |
`sin`에 대한 정의되지 않은 참조 (0) | 2020.09.04 |
상수는 정적으로 표시 할 수 없습니다. (0) | 2020.09.04 |