如果要绑定到特定的事件,您可以使用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.youkuaiyun.com/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