typescript – 如何从Angular2中的父组件类访问子组件类?

前端之家收集整理的这篇文章主要介绍了typescript – 如何从Angular2中的父组件类访问子组件类?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在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
    }
}

在这个例子中,我如何从Parent组件的构造函数或一些回调函数调用Child组件的doSomething()方法.

解决方法

这很简单,但你必须记住几点,我将在下面详细介绍,首先是代码.

要引用您的孩子,在这种情况下,您希望您的孩子在您的视图中,所以您必须使用@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.

我希望它有帮助:)

猜你在找的Angularjs相关文章