在角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
}
}在本例中,如何从Child组件的构造函数或回调函数调用Parent组件的doSomething()方法。
发布于 2015-11-02 22:09:48
这很简单,但您必须记住几点,下面我将详细介绍,首先是代码。
要引用您的子视图,在这种情况下,您希望您的子视图在视图中,所以您必须使用@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();
}
}
}Note
如果您要转到ES6,afterViewInit()内部的循环将工作,因为angular2内部使用Symbol.iterator。如果您正在转换到ES5,您将不得不解决它,因为类型记录does not support it (见plnkr的解决办法)。
这是plnkr。
我希望它有帮助:)
发布于 2016-09-02 15:01:39
您可以在父组件中使用@ViewChild来访问子组件的任何方法。
@Component({
selector: 'parent',
directives: [Child]
})
export class Parent {
@ViewChild(Child) childComponent: Child;
ngAfterViewInit() {
// The child is available here
childComponent.doSomething();
}
} 注意:此代码片段用于angular2 rc4版本。
https://stackoverflow.com/questions/33486747
复制相似问题