【问题标题】:How to access a child component class from the parent component class in Angular2?如何从Angular2中的父组件类访问子组件类?
【发布时间】:2016-02-02 21:00:18
【问题描述】:

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

【问题讨论】:

    标签: typescript angular


    【解决方案1】:

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

        @Component({
          selector: 'parent',
          directives: [Child]
        })
    
        export class Parent {
            @ViewChild(Child) childComponent: Child;
    
            ngAfterViewInit() {
            // The child is available here
            childComponent.doSomething();
          }
        } 
    

    注意:此代码 sn-p 适用于 angular2 rc4 版本。

    【讨论】:

      【解决方案2】:

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

      要引用您的孩子,在这种情况下,您希望您的孩子在您的视图中,因此您必须使用 @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,则必须从 typescript does not support it 开始解决它(有关解决方法,请参见 plnkr)。

      这是plnkr

      希望对你有帮助:)

      【讨论】:

      • 就我而言,我只有一个子组件,所以我只使用this.children.first。谢谢!
      • @rob 如果您只需要一个子组件,请使用@ViewChild 而不是@ViewChildren
      • 哦,更好。谢谢
      • 有没有办法使用 ID 或其他方式访问特定的孩子?就像 JS 中的 getElementById 一样。
      • 这里的备忘单angular.io/cheatsheet 中也写着“不适用于指令”。还有其他方法可以做到这一点吗?
      猜你喜欢
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 2016-05-29
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 2017-04-22
      • 2016-12-02
      相关资源
      最近更新 更多