Reputation: 1433
This is my parent component:
import {Component, Input} from 'angular2/core';
import {ChildComponent} from '../../components/parent-child-and-child-parent-communication/child';
@Component({
selector: 'parent-component',
template: `<li *ngFor="#position of employees">
{{position.name}}</li>
<child-component name="Accenture"></child-component>
Clicked data {{clicked}}`,
directives:[ChildComponent]
})
export class ParentComponent{
employees;
@Input() clicked;
constructor(){
this.employees = [{
id: 1,
name: "software developer"
},
{
id: 2,
name: "Team Leader"
},
{
id: 3,
name: "Project "
}
]
}
}
This is my child component:
import {Component, Input, Output, EventEmitter} from 'angular2/core';
@Component({
selector: 'child-component',
template: `office name: {{name}}. <br> chennai office list<br> <li *ngFor="#office of offices" (click)="selectOffice(office)">
{{office.name}}</li>`
})
export class ChildComponent{
selectedOffice;
@Input() name;
@Output() clicked = new EventEmitter()
offices;
officename;
constructor(){
this.offices = [
{
id: 1,
name: "HCL Technology"
},
{
id: 2,
name: "Accenture"
},
{
id: 3,
name: "TCS"
}
]
}
selectOffice(data) {
console.log(data)
this.officename = data;
this.clicked.emit(this.officename)
}
}
I want to send clicked office name to parent component and display it How to fix this issue? Otherwise please explain how to send data from one component to other component while click event triggers.
Upvotes: 1
Views: 306
Reputation: 202176
You could try this to execute a method when the clicked
event occurs within the child component:
@Component({
selector: 'parent-component',
template: `
<li *ngFor="#position of employees">
{{position.name}}
</li>
<child-component (clicked)="displayClickedData($event)"
name="Accenture"></child-component>
Clicked data {{clicked}}
`,
directives:[ChildComponent]
})
export class ParentComponent {
displayClickedData(data) {
this.clicked = data;
}
}
The $event
value corresponds to the value used when triggered the event. In your case: this.officename
.
Notice that it's not necessary to have @Input
for the clicked
property.
Upvotes: 1