Output
The "Notify Me" button doesn't do anything yet. In this section, you'll set up the product alert component so that it emits an event up to the product list component when the user clicks "Notify Me". You'll define the notification behavior in the product list component.
Open product-alerts.component.ts.
Import Output and EventEmitter from @angular/core:
src/app/product-alerts/product-alerts.component.tscontent_copyimport { Component } from '@angular/core';import { Input } from '@angular/core';import { Output, EventEmitter } from '@angular/core';
In the component class, define a property named notify with an
@Output decorator and an instance of event emitter. This makes it possible for the product alert component to emit an event when the value of the notify property changes.
content_copyexport class ProductAlertsComponent { @Input() product; @Output() notify = new EventEmitter();}
In the product alert template (product-alerts.component.html), update the "Notify Me" button with an event binding to call the notify.emit() method.
src/app/product-alerts/product-alerts.component.htmlcontent_copy<p *ngIf="product.price > 700"> <button (click)="notify.emit()">Notify Me</button></p>
Next, define the behavior that should happen when the button is clicked. Recall that it's the parent (product list component)—not the product alerts component—that's going to take the action. In the product-list.component.ts file, define an onNotify() method, similar to the share() method:
src/app/product-list/product-list.component.tscontent_copyexport class ProductListComponent { products = products; share() { window.alert('The product has been shared!'); } onNotify() { window.alert('You will be notified when the product goes on sale'); }}
Finally, update the product list component to receive output from the product alerts component.
In product-list.component.html, bind the app-product-alerts component (which is what displays the "Notify Me" button) to the onNotify() method of the product list component.
src/app/product-list/product-list.component.htmlcontent_copy<button (click)="share()"> Share</button><app-product-alerts [product]="product" (notify)="onNotify()"></app-product-alerts>
Try out the "Notify Me" button:
Learn more: See Component Interaction for more information about listening for events from child components, reading child properties or invoking child methods, and using a service for bi-directional communication within the family.