我有一个组件可以在单击关闭按钮时从页面中删除。我已经暴露了一个testClose
事件,用户可以在组件关闭时注册以执行某些工作。当组件关闭时,如何注册该事件以调用函数?例如,当TestComponent关闭时,我想将closeCounter增加1。这是plnkr:
https://plnkr.co/edit/iGyzIkUQOTCGwaDqr8o0?p=preview
暴露事件的TestComponent:
import {Component, Input, Output, EventEmitter} from 'angular2/core';
@Component({
selector: 'test',
template: `
<div class="box" *ngIf="!_close">
<button class="close" (click)="close()">x</button>
</div>
`,
styles:[
`
.box{
background: yellow;
height: 100px;
width: 100px;
}
`
]
})
export class TestComponent{
@Input("testClose") _close = false;
@Output("testCloseChange") _closeChange = new EventEmitter<boolean>(false);
close(): void{
this._close = true;
this._closeChange.emit(true);
}
open(): void{
this._close = false;
this._closeChange.emit(true);
}
}
App Component应该注册到TestComponent的close事件来调用某个函数。
import {Component} from 'angular2/core';
import {TestComponent} from './test.component';
@Component({
selector: "my-app",
template: `
<div class="container">
<test [testClose]="isClose"></test>
Close Count: {{closeCount}}
</div>
`,
directives: [TestComponent]
})
export class AppComponent{
isClose: boolean = false;
closeCount: number = 0;
incrementClose(): void{
this.closeCount++;
}
}
答案 0 :(得分:6)
只需为正在发出的事件添加一个侦听器
(testCloseChange)="onTestCloseChange($event)"
因此,应用程序组件模板将如下所示
<div class="container">
<test [testClose]="isClose" (testCloseChange)="onTestCloseChange($event)"></test>
Close Count: {{closeCount}}
</div>
在App组件类中,您应该定义onTestCloseChange
export class AppComponent{
onTestCloseChange(event) {
}
}