programing

@viewchild를 사용하여 여러 뷰 하위 항목에 액세스합니다.

showcode 2023. 4. 25. 23:48
반응형

@viewchild를 사용하여 여러 뷰 하위 항목에 액세스합니다.

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부터@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̶ 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.

언급URL : https://stackoverflow.com/questions/40165294/access-multiple-viewchildren-using-viewchild 입니다.

반응형