angular2 指令“无法使用输出元数据读取未定义的属性“订阅"

编程入门 行业动态 更新时间:2024-10-25 17:15:20
本文介绍了angular2 指令“无法使用输出元数据读取未定义的属性“订阅"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

关于 Angular2 指令,我想使用 outputs 而不是 @Output 因为我有很多自定义事件并希望保持 DRY.

但是,我遇到了TypeError: Cannot read property 'subscribe' of undefined,我不知道为什么会这样.

这是使用该指令的应用组件

解决方案

需要初始化输出:

import { Directive } from "@angular/core";@指示({选择器:'[我的指令]',输出:['myEvent']})导出类 MyDirective {myEvent:EventEmitter= new EventEmitter();//<----构造函数(){console.log('>>>>>>>>> this.myEvent', this.myEvent);}}

你也可以使用 @HostListener 装饰器:

@Directive({选择器:'[我的指令]'})导出类 MyDirective {@HostListener('myEvent')myEvent:EventEmitter= new EventEmitter();//<-----构造函数(){console.log('>>>>>>>>> this.myEvent', this.myEvent);}}

Regarding Angular2 directive, I wanted to use outputs instead of using @Output because I have many custom events and wanted to keep DRY.

However, I am having TypeError: Cannot read property 'subscribe' of undefined, and I don't know why it's happening.

http://plnkr.co/edit/SFL9fo?p=preview

import { Directive } from "@angular/core";

@Directive({
  selector: '[my-directive]',
  outputs: ['myEvent']
}) 
export class MyDirective {
  constructor() {
    console.log('>>>>>>>>> this.myEvent', this.myEvent);
  }
}

And this is app component that uses this directive

解决方案

You need to initialize the output:

import { Directive } from "@angular/core";

@Directive({
  selector: '[my-directive]',
  outputs: ['myEvent']
}) 
export class MyDirective {
  myEvent:EventEmitter<any> = new EventEmitter(); // <-----

  constructor() {
    console.log('>>>>>>>>> this.myEvent', this.myEvent);
  }
}

You could also use the @HostListener decorator:

@Directive({
  selector: '[my-directive]'
}) 
export class MyDirective {
  @HostListener('myEvent')
  myEvent:EventEmitter<any> = new EventEmitter(); // <-----

  constructor() {
    console.log('>>>>>>>>> this.myEvent', this.myEvent);
  }
}

这篇关于angular2 指令“无法使用输出元数据读取未定义的属性“订阅"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-22 23:01:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1031276.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指令   属性   未定义   数据   quot

发布评论

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

>www.elefans.com

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