[英]Angular 2 call a function/method when an event is emitted
I have a component which can be removed from the page when a close button is clicked. 我有一个组件,单击关闭按钮后可以从页面中删除它。 I have exposed a
testClose
event that a user can register to do some work when the component is closed. 我公开了一个
testClose
事件,当关闭组件时,用户可以注册该记录以执行某些工作。 How do I register to that event to call a function when the component is closed? 关闭组件后,如何注册该事件以调用函数? For example, I would like to increment the closeCounter by 1 when the TestComponent is closed.
例如,当TestComponent关闭时,我想将closeCounter递增1。 Here is the plnkr:
这是plnkr:
https://plnkr.co/edit/iGyzIkUQOTCGwaDqr8o0?p=preview https://plnkr.co/edit/iGyzIkUQOTCGwaDqr8o0?p=preview
TestComponent which exposes an event: 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 which should register to the close event of the TestComponent to call some function. 应注册到TestComponent的close事件以调用某些功能的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++;
}
}
Just add a listener to the event being emitted 只需向正在发出的事件添加一个侦听器
(testCloseChange)="onTestCloseChange($event)"
So app component template will look like this 因此,应用程序组件模板将如下所示
<div class="container">
<test [testClose]="isClose" (testCloseChange)="onTestCloseChange($event)"></test>
Close Count: {{closeCount}}
</div>
And inside the App component class you should define the onTestCloseChange 在App组件类中,您应该定义onTestCloseChange
export class AppComponent{
onTestCloseChange(event) {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.