import { Component,OnInit } from '@angular/core';
@Component({
selector: 'app-parent',templateUrl: './parent.component.html',styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
contacts:any=[];
constructor() { }
ngOnInit() {
this.contacts=[
{title:'s',good:1},{title:'ss',good:11},{title:'sss',good:111},{title:'ssss',good:1111}
];
}
childOutEvent(ev,i){
this.contacts[i].good += ev;
}
}
<p> parent works! </p> <ul> <li *ngFor="let contact of contacts;let i = index"> <app-child [contact]="contact" (OutEvent)="childOutEvent($event,i)" ></app-child> </li> </ul>
import { Component,OnInit,Input,Output,EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',templateUrl: './child.component.html',styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@input() contact:any={};
@Output() OutEvent = new EventEmitter<number>();
constructor() { }
ngOnInit() {
}
good_to_parent(num){
this.OutEvent.emit(num);
}
}
{{contact.title}} - {{contact.good}}
<button (click)="good_to_parent(1)" >good +1</button>
<button (click)="good_to_parent(-1)" >good -1</button>
https://angular.cn/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child