2017-09-26 10 views
2

私はhierarhy:app.component> intro.component> header.componentにコンポーネントを持っています。 app.componentで定義されているheader.componentメソッドで使用します。私は@viewChildでそれを作る方法があることを認識しています。それを動作させる最も簡単な方法は何ですか?angular2他のコンポーネントのメソッドを使用

// edit header.component.htmlにあるhtmlタグの(click)イベントを実行したいと思います。この関数では、app.componentからメソッドを実行します。

+0

あなたは正しい方向にあります。 @ViewChildデコレータを使うべきです。 –

+0

app.componentで「初期化された」メソッドとはどういう意味ですか? header.component内のapp.componentで定義されたメソッドを呼び出す方法について質問していますか?それとも、header.componentに渡すapp.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 }

関連する問題