I've this code...It's a sample tutorial application I'm trying to build that's reflect the daily basis needs of a developer. Actually, when the user types "fire" on the parent component, the child execute an event that's sends to the parent the word "booom" - It's a sample to demonstrate communication between a child component sending messages to a parent component using @Input and OnChanges.
Now, I'm trying to do different: The parent should with some how tell to the child a message like "Target Locked" to the child when the user press the enter key (keyCode == 13). With this we will have a scenario of 2 way communication between components.
What is the best approach ?
child.component
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 !!!");
}
}
}
parent.component
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()
to communicate from the parent to the child, and@Output()
to communicate from the child to the parent, or use a service. – Eric Martinez