2017-09-26 6 views
2

hierarhy : app.component> intro.component> header.component에 구성 요소가 있습니다. app.component에 정의 된 header.component에서 사용하려고합니다. @viewChild를 사용하는 방법이 있다는 것을 알고 있습니다. 작동시키는 가장 쉬운 방법은 무엇입니까?angular2 다른 구성 요소의 방법 사용

// 편집 header.component.html에있는 html 태그에 이벤트 (클릭)를하고 싶습니다. 이 함수에서는 app.component에서 메소드를 실행하려고합니다.

+0

당신은 올바른 방향이다. @ViewChild 데코레이터를 사용해야합니다. –

+0

app.component에서 '초기화 됨'메서드는 무엇을 의미합니까? header.component의 app.component에 정의 된 메소드를 호출하는 방법에 대해 묻는 중입니까? 아니면 app.component에서 초기화 된 '속성'이 header.component에 전달되는 것입니까? – amal

+0

나는 그 방법이 정의되었다는 것을 의미했다. 업데이트 된 게시물, 감사합니다 –

답변

0

가능한 예 : app.component.html의 HTML에서

:

...<app-intro></app-intro> 

intro.compoennt.html에서 HTML :

...<app-header #header></app-header> 

및 app.component에서 .ts :

@ContentChild("header") 
public headerComponent: HeaderComponent; 

체 CK https://angular.io/api/core/ContentChild

+0

다른 가능한 시나리오는 개체를 전달하는 컨트롤에 주입 할 수있는 서비스를 사용하는 것입니다. – ForestG

+0

@ViewChild ("header")를 선언하는 이유 private headerComponent : HeaderComponent; app.component에서 header.component의 메소드를 실행하고 싶습니다. –

+0

죄송합니다. 문제가 있습니다. 컨트롤 밖에 서 사용하고 싶다면 공개로 선언해야합니다. – ForestG

1

@input이 (스타일 반응)으로 또한 하위 구성 요소에 콜백 함수를 전달할 수 있습니다

\t //app.component.html: 
 

 
\t <app-intro [appMethod] = "boundMethod"></app-intro> 
 

 
\t export class AppComponent { \t 
 

 
\t  ngOnInit() { 
 
       this.boundMethod = this.appMethod.bind(this); 
 
\t  } 
 

 
\t  appMethod() { 
 
       console.log("appMethod called"); 
 
\t  } 
 
\t } 
 

 

 
\t //intro.component: 
 

 
\t <app-header [appMethod] = "appMethod"></app-header> 
 

 
\t export class IntroComponent { 
 
\t  @Input() public appMethod: Function; 
 
\t } 
 

 
\t //header.component: 
 

 
\t export class HeaderComponent { 
 
\t  @Input() appMethod: Function; 
 
\t  ngOnInit() { 
 
       appMethod(); // Call parent method 
 
\t  } 
 
\t }

관련 문제