Call child component method from parent class - Angular
You can do this by using @ViewChild
for more info check this link
With type selector
child component
@Component({ selector: 'child-cmp', template: '<p>child</p>'})class ChildCmp { doSomething() {}}
parent component
@Component({ selector: 'some-cmp', template: '<child-cmp></child-cmp>', directives: [ChildCmp]})class SomeCmp { @ViewChild(ChildCmp) child:ChildCmp; ngAfterViewInit() { // child is set this.child.doSomething(); }}
With string selector
child component
@Component({ selector: 'child-cmp', template: '<p>child</p>'})class ChildCmp { doSomething() {}}
parent component
@Component({ selector: 'some-cmp', template: '<child-cmp #child></child-cmp>', directives: [ChildCmp]})class SomeCmp { @ViewChild('child') child:ChildCmp; ngAfterViewInit() { // child is set this.child.doSomething(); }}
This Worked for me ! For Angular 2 , Call child component method in parent component
Parent.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { ChildComponent } from '../child/child'; @Component({ selector: 'parent-app', template: `<child-cmp></child-cmp>` }) export class parentComponent implements OnInit{ @ViewChild(ChildComponent ) child: ChildComponent ; ngOnInit() { this.child.ChildTestCmp(); } }
Child.component.ts
import { Component } from '@angular/core';@Component({ selector: 'child-cmp', template: `<h2> Show Child Component</h2><br/><p> {{test }}</p> ` })export class ChildComponent { test: string; ChildTestCmp() { this.test = "I am child component!"; } }
I think most easy way is using Subject. In below example code, the child will be notified each time 'tellChild()' is called.
Parent.component.ts
import {Subject} from 'rxjs/Subject';...export class ParentComp { changingValue: Subject<boolean> = new Subject(); tellChild() { this.changingValue.next(true); }}
Parent.component.html
<my-comp [changing]="changingValue"></my-comp>
Child.component.ts
...export class ChildComp implements OnInit{ @Input() changing: Subject<boolean>; ngOnInit(){ this.changing.subscribe(v => { console.log('value is changing', v); }); }}
Working sample on Stackblitz