rob*_*rob 4 typescript angular
在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
}
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我如何从组件的构造函数或一些回调函数中调用Child组件的doSomething()方法Parent.
这很简单,但你必须记住几点,我将在下面详细介绍,首先是代码.
要引用您的孩子,在这种情况下,您希望您的孩子在您的视图中,所以您必须使用@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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意
afterViewInit()如果您在angular2内部使用时转换为ES6,则内部循环将起作用Symbol.iterator.如果你要转换到ES5,你必须解决它,因为typescript 不支持它(请参阅plnkr的解决方法).
这是plnkr.
我希望它有帮助:)
| 归档时间: |
|
| 查看次数: |
2372 次 |
| 最近记录: |