在Angular 2中,如何从父组件类访问子组件类?例如
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 } }
解决方法
这很简单,但你必须记住几点,我将在下面详细介绍,首先是代码.
要引用您的孩子,在这种情况下,您希望您的孩子在您的视图中,所以您必须使用@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(); } } }
注意
如果您要转换为ES6,则afterViewInit()内部的循环将起作用,因为angular2内部使用Symbol.iterator
.如果您要转换为ES5,则必须解决它因为typescriptdoes not support it(请参阅plnkr foraroundaround).
这是plnkr.
我希望它有帮助:)