2017-01-18 8 views
1

템플릿을 거치지 않고 부모 타이프 스크립트 파일에 일부 데이터를 직접 내보내려는 중첩 구성 요소가 있습니다. 사용할 수 없습니다<child (childEvent)="parentFunc()"></child>각도 2 : 자식 구성 요소의 스크립트 파일로 직접 자식 구성 요소를 내 보냅니다.

이게 가능합니까? 그렇다면 어떻게?

이것은 현재 상태입니다.

parent.component.html

<child #child> </child> 

parent.component.ts (요소는이 있어야)

@ViewChild('child') public child; 

public doSomething() { 
    this.child.work(); 
} 

public doThisWhenChildEmits(someData) { 
    //?????How do I call this function from child without going through the DOM 
    alert(It worked) 
} 

child.component.ts

당신이 사용하지 않을 경우3210

답변

1

@Output 대신 Subject을 사용할 수

부모 변경에 가입한다. 부모에서, 구성 요소의 주제를 선언하고 생성자의 변화에 ​​가입 :

public static changesMade: Subject<any> = new Subject(); 

//inside constructor the following 
ParentComponent.changesMade.subscribe(res => { 
    //call your method here, with the res (someData) you receive from child 
    this.doThisWhenChildEmits(res); 
}); 

자녀의를 :

public clickToSendBack(){ 
    // send the data to parent 
    ParentComponent.changesMade.next(someData) 
} 

이 도움이되는지 알려주세요! :)

+0

감사합니다. 귀하의 답변이 효과가 있다고 생각합니다. 최선을 다하기 전에 며칠을주고 싶습니다. –

+0

물론, 이해합니다! :) – Alex