2016-08-01 9 views
2

이 호스트 구성 요소 코드를 상상?전화 중첩 된 구성 요소의 기능 angular2

+0

더 많은 코드를 제공해주십시오. 'save()'와'waitingForHostComp()'는 어디에 있습니까? –

+0

'save()'는 ChildComponent를 가져 오는 ParentComponent에있다. 'waitingForHostComp()'는 ChildComponent에있다. 기본적으로 ChildComponent의 Listener는 ParentComponent (ChildComponent를 주입)가 서버로부터 응답을받을 때 트리거됩니다. – nottinhill

답변

6

할 수있는 방법은 ViewChild입니다. 즉, 하위 구성 요소를 부모에게 ViewChild으로 삽입합니다.

import { ViewChild } from '@angular/core'; 
import { Component } from '@angular/core'; 
import { ChildComponent } from './child.component'; 

@Component({ 
    selector: 'parent-component', 
    template: ` implements AfterViewInit 
    <child-component></child-component> 
    `, 
    directives: [ChildComponent] 
}) 
export class ParentComponent { 
    @ViewChild(ChildComponent) 
    private childComponent: ChildComponent; 

    save(): void { 
     this.myService.myHTTPCall().subscribe((event) => { 
      this.childComponent.waitingForHostedComp(event); 
     }) 
    } 

} 

자세한 내용은 Component Interaction Cookbook: Parent Calls a ViewChild에서 확인할 수 있습니다.

+0

흥미 롭군요 ... 전에 사용한 것처럼 다른 입력 및 출력이 작동합니까 (이 코드 샘플에서 언급하지 않았습니다)? – nottinhill

+1

물론 이전과 같이 작동합니다. ViewChild는 타이프 스크립트 코드에서 자식 구성 요소와 상호 작용할 수있는 방법 일뿐입니다. –

+0

'private childComponent : ChildComponent;'를 생성자에 넣어야 만 완벽하게 작동합니다. 고마워, 베르나르도. – nottinhill

관련 문제