这是我的父组件:
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 "
}
]
}
}
这是我的孩子组成部分:
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)
}
}
我想将点击的办公室名称发送到父组件并显示它 如何解决这个问题?否则,请说明如何在单击事件触发器时将数据从一个组件发送到其他组件。
答案 0 :(得分:1)
您可以尝试在子组件中发生clicked
事件时执行此方法:
@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;
}
}
$event
值对应于触发事件时使用的值。在您的情况下:this.officename
。
请注意,@Input
属性没有必要clicked
。