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

标签 angular

我有一个组件,可以在单击关闭按钮时将其从页面中删除。我公开了一个 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/

相关文章:

typescript - AngularJs 2 中 AppComponent 和 @Component 之间的联系是什么?

angular - Angular 5 中可以注册多个拦截器吗?

node.js - Sqlite Electron : Error: SQLITE_CANTOPEN: unable to open database file

c# - 尝试上传具有 Angular 2 的文档时,Web API 中的文件计数始终为零

html - 如何在 Angular 4 中为 ng-template 标签提供样式?

html - Ionic 2/angular 2 - 如何将带有 Typescript 的 HTML 元素添加到我的组件中?

javascript - Angular 4 Material 对话框将对象数组传递到对话框

javascript - 如何为 Angular 2 博客文章设置不同模板的格式?

angular - 对象不支持属性或方法 'keys' - (IE11)

node.js - npm install 陷入困境 doParallel extraxt xxxx