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

In Angular 2, how do I access the child component class from the parent component class? eg.

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
    }
}

In this example, how can I call the Childcomponent method doSomething()from the component constructor Parentor some callback function.

+4
source share
2 answers

It's quite simple, but you need to consider a few points, which I will discuss below, first the code.

, , , @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();
    }
  }

}

afterViewInit() , ES6, angular2 Symbol.iterator. ES5, , typescript (. Plnkr ).

plnkr.

, :)

+7

@ViewChild .

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

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

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

. angular2 rc4.

+1

Source: https://habr.com/ru/post/1614196/


All Articles