发出事件时,Angular 2调用函数/方法

编程入门 行业动态 更新时间:2024-10-28 09:13:56
本文介绍了发出事件时,Angular 2调用函数/方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个组件,单击关闭按钮后可以从页面中删除它.我公开了一个 testClose 事件,当组件关闭时,用户可以注册该事件以执行某些工作.关闭组件后,如何注册该事件以调用函数?例如,当TestComponent关闭时,我想将closeCounter递增1.这是plnkr:

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. 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. Here is the plnkr:

plnkr.co/edit/iGyzIkUQOTCGwaDqr8o0?p=preview

暴露事件的TestComponent:

TestComponent which exposes an event:

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的close事件以调用某些功能的应用程序组件.

App Component which should register to the close event of the TestComponent to call some function.

import {Component} from 'angular2/core'; import {TestComponent} from './testponent'; @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>

在App组件类中,您应该定义onTestCloseChange

And inside the App component class you should define the onTestCloseChange

export class AppComponent{ onTestCloseChange(event) { } }

更多推荐

发出事件时,Angular 2调用函数/方法

本文发布于:2023-11-23 04:02:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620017.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   事件   方法   Angular

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!