2015-11-02 128 views
4

在Angular 2中,如何從父組件類訪問子組件類?例如如何在Angular2中從父組件類訪問子組件類

import {Component, View} from 'angular2/core'; 

@Component({selector: 'child'}) 
@View({template: `...`}) 
class Child { 
    doSomething() { 
     console.log('something'); 
    } 
} 

@Component({selector: 'parent'}) 
@View({ 
    directives: [Child], 
    template: `<child></child>` 
}) 
class Parent { 
    constructor() { 
     //TODO: call child.doSomething() when the child component is ready 
    } 
} 

在這個例子中,我怎麼會叫Child組件無論從Parent組件的構造或一些回調函數doSomething()方法。

回答

7

這很簡單,但你必須記住幾點,我將在下面詳細介紹,首先是代碼。

要引用你的孩子,在這種情況下,你希望你的視圖中你的孩子,所以你必須使用@ViewChildren,你必須等待視圖進行初始化,這樣你就

@Component({ 
    selector: 'hello', 
    template: `<child></child>`, 
    directives : [Child] 
}) 
export class Parent implements AfterViewInit { 
    @ViewChildren(Child) children: QueryList<Child>; 

    afterViewInit() { 
    for(let child of this.children) { 
     child.doSomething(); 
    } 
    } 

} 

注意

由於angular2在內部使用Symbol.iterator,因此如果您正在轉換爲ES6,則afterViewInit()內部的循環將可用。如果您正在轉換爲ES5,則必須自打字稿does not support it(請參閱plnkr for workaround)解決此問題。

這是plnkr

我希望它能幫助:)

+0

在我的情況下,我只有一個子組件,所以我只是使用'this.children.first'。謝謝! – rob

+3

@rob如果你只需要一個子組件,然後使用['@ ViewChild'](https://github.com/angular/angular/blob/2.0.0-alpha.45/modules/angular2/src/core/metadata /di.ts#L353)而不是'@ ViewChildren' – alexpods

+0

哦,甚至更好。謝謝 – rob

1

您可以使用@ViewChild你父組件accesss子組件的任何方法。

@Component({ 
     selector: 'parent', 
     directives: [Child] 
    }) 

    export class Parent { 
     @ViewChild(Child) childComponent: Child; 

     ngAfterViewInit() { 
     // The child is available here 
     childComponent.doSomething(); 
     } 
    } 

注意:此代碼片段用於angular2 rc4版本。

相關問題