Angular 2 ES6 - 从组件发送事件

时间:2016-05-09 09:56:10

标签: ionic-framework angular ecmascript-6 ionic2

我想从ES6中的Component发送自定义事件,因此我可以在模板<component (someEvent)="someFunction()">中收听它,但我无法实现。

@Component's属性ouputsevents正在破坏应用程序。我错过了什么吗?

这是我的组件声明:

import {Component, Output} from 'angular2/core';

@Component({
    selector: 'section-navigator-component',
    templateUrl: 'build/components/section_navigator/section_navigator.html',
    inputs: [ 'resources', 'attr' ],
    outputs: [ 'someEvent' ]
})


export class SectionNavigatorComponent {
    constructor() {

    }

    resourceClickHandler($event, resource) {

    }
}

2 个答案:

答案 0 :(得分:2)

这适用于您的情况:

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

@Component({
    selector: 'section-navigator-component',
    templateUrl: 'build/components/section_navigator/section_navigator.html',
    inputs: [ 'resources', 'attr' ],
    outputs: [ 'someEvent' ]
})


export class SectionNavigatorComponent {

    constructor() {
      this.someEvent = new EventEmitter();
    }

    resourceClickHandler($event, resource) {
      this.someEvent.emit(someValue);
    }
}

答案 1 :(得分:1)

除非使用下面的备用TypeScript语法,否则无需导入“输出”:

import {Component, Input, Output, EventEmitter} from 'angular2/core';

@Component({
    selector: 'section-navigator-component',
    templateUrl: 'build/components/section_navigator/section_navigator.html'
})


export class SectionNavigatorComponent {
    @Input() resources: any;
    @Input() attr: any;

    @Output() someEvent: EventEmitter<any> = new EventEmitter();

    constructor() {
    }

    resourceClickHandler($event, resource) {
      this.someEvent.emit(someValue);
    }
}