簡體   English   中英

如何從Angular2中的父組件類訪問子組件類?

[英]How to access a child component class from the parent component class in 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,你必須解決它,因為typescript 不支持它 (請參閱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版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM