2016-10-10 9 views
3

通常、@ViewChildを使用して親コンポーネントから子コンポーネントプロパティに簡単にアクセスできます。角2 - ルータアウトレットから生成された子コンポーネントプロパティへのアクセス

App.component.ts(親要素)

import { Component, ViewChild, AfterViewInit } from '@angular/core'; 
import { ChildComponent } from './child.component'; 
@Component({ 
    selector: 'my-app', 
    template: '<h1>My First Angular App</h1> <child-app></child-app>' 
}) 
export class AppComponent implements AfterViewInit { 
    @ViewChild(ChildComponent) childComponent: ChildComponent 

    ngAfterViewInit() { 
     console.log("This is app component "); 
     console.log(this.childComponent.name); 
    } 
} 

child.component.ts

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'child-app', 
    template: '<h2>This is my child</h2>' 
}) 
export class ChildComponent { 
    // some attribute 
    name: any = "Kid"; 

    callChild(): void{ 
     console.log("Hello, I am your son"); 
    } 
} 

子コンポーネントディレクティブが親コンポーネント内に直接ネストされている場合、それは簡単です。しかし、親コンポーネントで、routeを設定して子を動的に生成し、<router-outlet></router-outlet>を使用した場合、結果は未定義です。

これを実現する方法をご存知ですか?

+3

ルーターで追加されたコンポーネントによるバインドはサポートされていません。代わりに共有サービスを使用できます。 https://angular.io/docs/ts/latest/cookbook/component-communication.html –

答えて

0

あなたの目標が単にあなたの子供から値/方法にアクセスするだけであれば、単純にstaticキーワードを使うことができます。コードの変更を参照してください

import { Component, ViewChild, AfterViewInit } from '@angular/core'; 
    import { ChildComponent } from './child.component'; 
    @Component({ 
     selector: 'my-app', 
     template: '<h1>My First Angular App</h1> <child-app></child-app>' 
    }) 
    export class AppComponent implements AfterViewInit { 
     @ViewChild(ChildComponent) childComponent: ChildComponent 

     ngAfterViewInit() { 
      ChildComponent.callChild("PArent"); 
     } 
    } 


    child.component.ts 

    import { Component } from '@angular/core'; 

    @Component({ 
     selector: 'child-app', 
     template: '<h2>This is my child</h2>' 
    }) 
    export class ChildComponent { 
     // some attribute 
     name: any = "Kid"; 

     static callChild(txt:string): void{ 
      console.log("Inside child - Hello, from: " + txt); 
     } 
    } 
関連する問題