【发布时间】:2016-03-15 14:40:32
【问题描述】:
我有这段代码...这是我正在尝试构建的示例教程应用程序,它反映了开发人员的日常需求。 实际上,当用户在父组件上键入“fire”时,子组件会执行一个事件,该事件会向父组件发送单词“booom” - 这是一个示例,用于演示子组件之间使用 @Input 向父组件发送消息的通信和OnChanges。
现在,我正在尝试做一些不同的事情:当用户按下回车键 (keyCode == 13) 时,父母应该告诉孩子一个类似“目标锁定”的消息。有了这个,我们将有一个组件之间的 2 路通信场景。
什么是最好的方法?
子组件
import {Component, Input, OnChanges, EventEmitter,Output, Injectable} from 'angular2/core';
@Injectable()
@Component({
selector: 'child-component',
template: `<p>I'm the child component</p>
`
})
export class ChildComponent implements OnChanges {
@Input() txt: string;
@Output() aim: EventEmitter<any> = new EventEmitter();
ngOnChanges(changes: {[propName: string]: SimpleChange}) {
var t = changes['txt'].currentValue;
if(t == 'fire') {
console.log('Fire !!!');
this.aim.emit("booom !!!");
}
}
}
父组件
import {Component} from 'angular2/core';
import {ChildComponent} from './child.component'
@Component({
selector: 'parent-component',
directives : [ChildComponent]
template: `<p>I'm the parent component</p>
<input type="textbox" [(ngModel)]="theModel" (keydown)="arrow($event)">
<p>feedback: {{feedback}}</p>
<child-component txt="{{theModel}}" (aim)="feedback=$event"></child-component>
`
})
export class ParentComponent {
theModel;
feedback;
arrow (evt){
if(evt.keyCode ==13) {
//Need to cause an event on the child - a message like "Target Locked"
};
}
}
【问题讨论】:
-
使用
@Input()从父级与子级通信,@Output()从子级与父级通信,或使用服务。 -
“现在,我正在尝试做一些不同的事情:”——我看不出这里有什么不同。只需使用相同的输入和输出属性并发送不同的消息,或者添加另一组输入和输出属性。还可以查看Component Interaction cookbook
-
父级使用 import 和选择器
合并子级 ny。因此,父母可以从孩子那里捕获(目标)事件。我的怀疑是要反其道而行之:子捕获父事件。请记住,孩子永远不会拥有父母的选择器。这就是为什么它真的不同。明白了吗?
标签: angular angular2-directives