I am new to Angular 7
(2+) & trying my hands on @Input
& @Output
. However, passing data from Parent to Child component via @Input is understood & in place.
However, very basic on the other hand passing data from Child to Parent component via using @Output
concept is understood & but the implementation is not getting right.
Here is what I am trying. When a button is clicked in the Child component, a property in the parent component should be converted to Upper case & displayed.
ChildComponent.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', }) export class ChildComponent implements OnInit { @Input('child-name') ChildName: string; @Output() onHit: EventEmitter<string> = new EventEmitter<string>(); constructor() { } ngOnInit() {} handleClick(name): void { this.onHit.emit(name); }}
ChildComponent.html
<h1> child works! </h1> <button (click)="handleClick('eventEmitter')"> Click me! </button>
ParentComponent.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', }) export class AppComponent { title = 'my-dream-app'; customerName: string = ""; catchChildEvent(e) { console.log(e); }}
ParentComponent.html
<div style="text-align:center"> <app-child [child-name]="HelloChild"></app-child> //Trying to bind to Custom event of child component here <b (onHit)="catchChildEvent($event)"> <i> {{customerName}} </i> </b>
No error in console or binding
From the above snippet, when the button in Child Component is clicked the parent Component’s property CustomerName should get the value & displayed?
Example: https://stackblitz.com/edit/angular-3vgorr
Advertisement
Answer
You are emitting event from app-child
component so attach the handler for app-child
component to make it work.
<div style="text-align:center"> <app-child (onHit)="catchChildEvent($event)" [child-name]="HelloChild"></app-child> //Trying to bind to Custom event of child component here <b> <i> {{customerName}} </i> </b>
And within the ts file update value of cutomerName
property.
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', }) export class AppComponent { title = 'my-dream-app'; customerName: string = ""; catchChildEvent(e) { this.customerName = e; } }