我有一个组件,可以在单击关闭按钮时将其从页面中删除。我公开了一个 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);
}
}
应注册到 TestComponent 的关闭事件以调用某些函数的 App Component。
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++;
}
}
最佳答案
只需为正在发出的事件添加一个监听器
(testCloseChange)="onTestCloseChange($event)"
所以应用组件模板看起来像这样
<div class="container">
<test [testClose]="isClose" (testCloseChange)="onTestCloseChange($event)"></test>
Close Count: {{closeCount}}
</div>
在 App 组件类中你应该定义 onTestCloseChange
export class AppComponent{
onTestCloseChange(event) {
}
}
关于Angular 2 在发出事件时调用函数/方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38356676/