37

I have a parent component called program-page and it has a child component called program-item now I have a button on the program-item and what I want that button to do is to call a function on the parent component.. Im not sure how I would do something like this..

program-page.component.html

<app-program-header></app-program-header>
<app-week-display></app-week-display>
<app-program-item [item]="programItem"></app-program-item>

program-page.component.ts

someFunction()

program-item.component.html

<button>click me</button> // button I want to be able to call event on parent component

Im aware I could use an event emitter but Ive never used one before and not sure how I would implement it in this case, I havent seen any examples where clicking a button on a child component calls a function on the parent

any help would be appreciated!

Smokey Dawson
  • 8,827
  • 19
  • 77
  • 152

1 Answers1

81

Angular has Input and Output, which can be used to provide data to a child component and send events to a parent component respectively.

You can do something like this.

program-page.component.html

<app-program-header></app-program-header>
<app-week-display></app-week-display>
<app-program-item [item]="programItem" (someEvent)="someFunction($event)"></app-program-item>

program-item.component.ts

import { EventEmitter } from '@angular/core';
....
@Output() someEvent = new EventEmitter();

program-item.component.html

<button (click)="someEvent.emit('data')">click me</button>

Primitive usage of Input and Output Stackblitz example

Community
  • 1
  • 1
Pavan Bahuguni
  • 1,947
  • 1
  • 15
  • 21
  • 7
    In `program-page.component.html`, if you want to access the `data`, it actually should be `(someEvent)="someFunction($event)"` – Sinandro Jul 04 '19 at 07:34
  • It looks like the `@Output()` variable is defined in the parent component here. But in the given link its defined in the child component. Which one is right ? – Nikhil Nanjappa Nov 18 '19 at 15:44
  • 2
    @NikhilNanjappa you are right, it should be in the child component, stackblitz example is correct. Edited the answer. – Pavan Bahuguni Nov 20 '19 at 15:11