加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:50:12 所属栏目:安全 来源:网络整理
导读:在Angular 2中,如何从父组件类访问子组件类?例如 import {Component,View} from 'angular2/core';@Component({selector: 'child'})@View({template: `...`})class Child { doSomething() { console.log('something'); }}@Component({selector: 'parent'})@V
在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.

我希望它有帮助:)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读