angular2的组件传值Input和Output

前端之家收集整理的这篇文章主要介绍了angular2的组件传值Input和Output前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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

猜你在找的Angularjs相关文章