2017-01-31 8 views
6

저는 이것이 매우 기본적인 것 같지만 저는 Angular 2를 처음 사용했습니다.이 작업을 수행하는 가장 좋은 방법을 알고 싶습니다. 다른 방법들. 상위 컴포넌트에서 하위 컴포넌트의 함수를 호출하려고합니다. 그렇다면 내가 가진 :Angular 2는 부모 구성 요소의 하위 구성 요소에서 함수를 호출합니다.

<parent> 
    <child></child> 
</parent> 

... 그리고 child이 기능을 show() 또는 hide() 요구했다, 내가 parent에서 그 중 하나를 호출하는 방법? 템플릿의 내부

답변

19

: 구성 요소 (옵션 2)의 내부

import { ..., ViewChild, ... } from '@angular/core'; 

// ... 

export class ParentComponent { 
    @ViewChild('yourChild') child; 

    ngAfterViewInit() { 
     console.log('only after THIS EVENT "child" is usable!!'); 
     this.child.hide(); 
    } 
} 

:

import { ..., ViewChild, ... } from '@angular/core'; 
import { ..., ChildComponent, ... } from '....'; 

// ... 

export class ParentComponent { 
    @ViewChild(ChildComponent) child; 

    ngAfterViewInit() { 
     console.log('only after THIS EVENT "child" is usable!!'); 
     this.child.hide(); 
    } 
} 

공식 문서를 참조하십시오 구성 요소 (옵션 1)의 내부

<parent (click)="yourChild.hide()"> 
    <child #yourChild></child> 
</parent> 

: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-view-child

라이브 데커 : https://plnkr.co/edit/fEYwlKlkMbPdfx9IGXGR?p=preview

+0

우수. 따라서 @ViewChild에 클래스 이름을 전달할 때 템플릿에 의해 인스턴스화 된 ChildComponent를 자동으로 선택합니다. – BBaysinger

+0

정확하게, 나는 그것의 첫 번째 또는 마지막 경우 여러 자식 있는지 확실하지 않습니다. 하지만 여러 자식들에게'ViewChildren'을 사용할 수 있습니다! 같은 방식으로 이름이나 클래스를 사용합니다. – mxii

+2

데모 플 런커를 추가했습니다. 동일한 클래스의 자식이 여러 개 있으면 'ViewChild'가 처음 발견 된 자식을 선택합니다. ;) – mxii

1

어린이의 기능을 호출하려면 @ViewChild이 필요합니다. 그러나,/표시하는 구성 요소를 숨기기 위해, 당신은 템플릿 내에서이 문제를 해결하는 것이 더 낫다 :

<parent> 
    <button (click)="showChild=!showChild">Toggle child</button> 
    <child *ngIf="showChild"></child> 
</parent> 

사용자 정의 기능 hide()을 선언하는 필요 없음을.

관련 문제