Output

如果要绑定到特定的事件,您可以使用Angular 2中的新事件语法,但如果您需要自己的自定义事件怎么办? 比如value的改变,和提交时出发事件

Output相当于指令的方法绑定,子作用域触发事件执行响应函数,而响应函数方法体则位于父作用域中,相当于将事件“输出到”父作用域中,在父作用域中处理。

一般思路; 1、导入output,并定义一个EventEmitter类 2、发送改变的 value 或者 index... 3、再父模板中设置监听 4、在父模板中 调用函数

父组件

//app.component.html
<app-child [values]="data" (childEvent) = "getChildEvent($event)">
</app-child>

//app.component.ts
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  data = [1,2,3];

  getChildEvent(index){
    console.log(index);
    this.data.splice(index,1);
  }
}

子组件

//app-child.component.html
<p *ngFor="let item of values; let i = index" (click)="fireChildEvent(i)">
  {{item}}
</p>


//app-child.component.ts
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  @Input() values;
  @Output() childEvent = new EventEmitter<any>();
  constructor() { }

  ngOnInit() {

  }
  fireChildEvent(index){
    this.childEvent.emit(index);
  }
}

效果

这里写图片描述

源码:https://github.com/own1991/angular2-demo

参考:http://blog.csdn.net/u014291497/article/details/60970792  Angular2中Input和Output用法及示例          及 http://learnangular2.com/outputs/  及 https://toddmotto.com/component-events-event-emitter-output-angular-2

详细讲解:http://www.concretepage.com/angular-2/angular-2-custom-event-binding-eventemitter-example

转载于:https://my.oschina.net/u/3427060/blog/1154240

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值