2015-11-02 149 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版本。

相关问题