【问题标题】:Angular 2 ES6 - Sending event from componentAngular 2 ES6 - 从组件发送事件
【发布时间】:2016-09-03 21:49:16
【问题描述】:

我想在 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) {

    }
}

【问题讨论】:

  • 请添加代码来演示您尝试过的内容以及失败的地方。您收到错误消息了吗?
  • 我已经更新了问题
  • 您是否正确导入了 someEvent?
  • 导入是什么意思? someEvent 是否必须是扩展某些基本 Event 类的类?
  • 好吧,我认为组件装饰器中没有关键输入或输出,但我想我错过了一些东西,因为 API 仍然发生了很大变化。是的,通常你会在@Input()@Output() 类中使用它来处理angular.io/docs/ts/latest/api/core/Input-var.html 事件,不要忘记从角度核心导入输入和输出装饰器

标签: ionic-framework angular ecmascript-6 ionic2


【解决方案1】:

这应该适用于您的情况:

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);
    }
}

【讨论】:

  • 谢谢,感谢您的回答,我能够解决我的问题。你很亲密,唯一缺少的是import {EventEmitter} from 'angular2/core'
  • 遗憾的是它没有抛出任何错误。总之谢谢
【解决方案2】:

除非您使用下面的备用 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);
    }
}

【讨论】:

    猜你喜欢
    • 2018-06-01
    • 2021-11-11
    • 2018-07-07
    • 2019-11-22
    • 1970-01-01
    • 2017-08-28
    • 2017-10-19
    • 2016-06-05
    • 2016-12-06
    相关资源
    最近更新 更多