code into child component mycomponent.ts
import { Component, OnInit , EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-mycomponent',
template: `
<button (click)="clickchild()">Click me!</button>
`
})
export class MycomponentComponent {
@Output() clicked = new EventEmitter<string>();
clickchild() {
this.clicked.emit('This is Child Component Code!');
}
}
Passing data into parent component app.component.ts
import { Component , EventEmitter, Output } from '@angular/core';
import { MycomponentComponent } from './mycomponent.component';
@Component({
selector: 'app-root',
template: `
<h2>sdsd</h2>
<app-mycomponent (clicked)="onClicked($event)"></app-mycomponent>
<p>{{childdata}}</p>
`
})
export class AppComponent {
childdata= '';
onClicked(value: string) {
this.childdata = value;
}
}
My Question is ->
why we again define onClicked function and pass a string into Parent Component ,
childdata= '';
onClicked(value: string) {
this.childdata = value;
}
although we have already did that in to child component we have defined function there
clickchild() {
this.clicked.emit('This is Child Component Code!');
}
The Childcomponent emits a click event. The click event of your childcomponent is emitting a String, as you defined here:
@Output() clicked = new EventEmitter<string>();
clickchild() {
this.clicked.emit('This is Child Component Code!');
}
The payload of the event (a string in this case), can then be accessed by the parameter $event. You subscribe in your parent component to the click event by:
<app-mycomponent (clicked)="onClicked($event)"></app-mycomponent>
onClicked(value: string) {
this.childdata = value;
}
So the child component emits a click event, but it has to be recognized by the parent component (utilizing subscription), otherwise the parent would not know about the emitted event.
See here for the docs: https://angular.io/api/core/EventEmitter
Sagat
During the click event of the child, one might want to notify the parent component that the child is being clicked. That is why we listen to the clicked event of the child in the parent. But the action that has to be done can (in your case it is to set some local state of a member) be done in either of the parent or the child depending on the app's need and properties that have to read or modified [because they might be present either the child or parent depending on the app architecture].
If you prefer the parent component need not the notified by the child's click, its better you don't listen to it and make appropriate changes in the child event listener itself.