如何在 Angular2 中从父组件 class 访问子组件 class?

How to access a child component class from the parent component class in Angular2?

在Angular 2中如何从父组件class访问子组件class?例如

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() 方法。

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

要引用你的 children,在这种情况下你希望你的 children 在你的视图中,所以你必须使用 @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. If you are transpiling to ES5 you'll have to workaround it since typescript does not support it(请参阅 plnkr 了解解决方法)。

这是 plnkr

希望对您有所帮助:)

您可以在父组件中使用 @ViewChild 来访问子组件的任何方法。

    @Component({
      selector: 'parent',
      directives: [Child]
    })

    export class Parent {
        @ViewChild(Child) childComponent: Child;

        ngAfterViewInit() {
        // The child is available here
        childComponent.doSomething();
      }
    } 

注意:此代码片段适用于angular2 rc4 版本。