在组件的模板中使用eventEmitter.emit()

时间:2018-03-19 15:26:08

标签: angular components eventemitter

修改

我在HTML模板中引用了同名的TemplateRef

<ng-template #eventEmitter>

对此抱歉,仍然保留引用错误代码的问题。

旧问题

我试图在组件的模板something.component.html中使用EventEmitter实例的emit()方法

<div (click)="eventEmitter.emit()">click me</div>

并在我的组件something.component.ts中定义,如

@Output() eventEmitter = new EventEmitter<any>();

并收到以下错误

"jit_nodeValue_3(...).emit is not a function"

我无法在the docguide中找到对此的任何引用,并对此行为感到好奇,有人有真正的解释吗?

1 个答案:

答案 0 :(得分:0)

EventEmitter上设置Output

import { Component, Output, EventEmitter } from '@angular/core';

@Component({
    selector: 'demo',
    template: `<h1>Demo</h1>
    <button (click)="notify.emit('hello')">Notify</button>`
})
export class DemoComponent {
    @Output() notify = new EventEmitter<any>();
}

订阅活动:

import { Component } from '@angular/core';

@Component({
    selector: 'app',
    template: `<h1>App</h1>
    <demo (notify)="receiveNotification($event)"></demo>`
})
export class AppComponent {
    notifications = new Array<any>();

    receiveNotification(notification: any) {
        this.notifications.push(notification);
    }
}

完整example in StackBlitz