Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Event from child component to parent component Angular 5

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!

like image 507
Smokey Dawson Avatar asked Feb 21 '18 02:02

Smokey Dawson


People also ask

How will you send data from a child component to the parent component?

To pass data from child to parent component in React:Pass a function as a prop to the Child component. Call the function in the Child component and pass the data as arguments. Access the data in the function in the Parent .

Which decorator lets a child component expose an event to a parent component?

The @Output() decorator in a child component or directive lets data flow from the child to the parent. @Output() marks a property in a child component as a doorway through which data can travel from the child to the parent.


1 Answers

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

like image 56
Pavan Bahuguni Avatar answered Sep 24 '22 04:09

Pavan Bahuguni