Angular 2 call a function in a child component from its parent component

I think this is really basic, but I'm new to Angular 2, and I would like to know how to do this, and if there are different ways. I am trying to call a function in a child component from its parent component. Therefore, if I have:

<parent> <child></child> </parent> 

... and child has functions called show() or hide() , how can I call any of them from parent ?

+7
angular typescript
source share
2 answers

Inside your template:

 <parent (click)="yourChild.hide()"> <child #yourChild></child> </parent> 

Inside your component (option1):

 import { ..., ViewChild, ... } from '@angular/core'; // ... export class ParentComponent { @ViewChild('yourChild') child; ngAfterViewInit() { console.log('only after THIS EVENT "child" is usable!!'); this.child.hide(); } } 

Inside your component (option2):

 import { ..., ViewChild, ... } from '@angular/core'; import { ..., ChildComponent, ... } from '....'; // ... export class ParentComponent { @ViewChild(ChildComponent) child; ngAfterViewInit() { console.log('only after THIS EVENT "child" is usable!!'); this.child.hide(); } } 

See white papers: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-view-child

live demo plunker: https://plnkr.co/edit/fEYwlKlkMbPdfx9IGXGR?p=preview

+21
source share

To call the function of the child, you need @ViewChild . However, to show / hide the component, you better solve this in the template:

 <parent> <button (click)="showChild=!showChild">Toggle child</button> <child *ngIf="showChild"></child> </parent> 

There is no need to declare a custom hide() function.

+1
source share

All Articles