简体   繁体   English

Angular 从指令发出事件时事件发射器不工作

[英]Angular eventemitter not working when emitting the event from directive

appcomp.html appcomp.html

`<app-child (callemit) = parentFunc($event)> </app-child>`

appcomp.ts appcomp.ts

` `

import { Component, OnInit, EventEmitter } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.comp.html'
})
export class AppComponent {
  ngOnInit() {}
  parentFunc(event){
    console.log(event)
  }
}

` `

childcomp.html childcomp.html

<a href='' [mydirective]="val"> </a>

childcomp.ts childcomp.ts

` `

@Component({
  selector: 'app-child',
  templateUrl: './app.child.component.html'
})

` `

mydirective.ts我的指令.ts

` `

import { Directive, ElementRef, Input, Output, HostListener, EventEmitter } from '@angular/core';

@Directive({
    selector: '[myDirective]'
})
export class myAppDirective {
    constructor() {}
    @Input ('myDirective') val: string;
    @Output() callEmit = new EventEmitter();
    @HostListener('click')
    onClick() {
     event.preventDefault();
     this.callEmit.emit({event , val});
    }
}

` In the above code i am trying to call parentFunc from appcomp using eventemitter and not able to get this work. ` 在上面的代码中,我试图使用 eventemitter 从 appcomp 调用 parentFunc,但无法完成这项工作。 Please let me know what is wrong here.请让我知道这里出了什么问题。

I think you most call callEmit on child component 我认为您最常在子组件上调用callEmit

childcomp.html childcomp.html

<a href='' [mydirective]="val" (callEmit)="childFunc($event)"> </a>

and in child Component emit the CallEmit Which called from appComp 并在子组件中发出从appComp调用的CallEmit

childcomp.ts 子组件

@Output() callEmit = new EventEmitter();

childFunc(){
this.callEmit.emit();
}

and finally use 最后使用

appCom.html appCom.html

`<app-child (callemit) = parentFunc($event)> </app-child>`

appcom.ts 应用程序

 parentFunc(event){
    console.log(event)
  }

https://stackblitz.com/edit/angular-exxhms https://stackblitz.com/edit/angular-exxhms

<a href='#' mydirective (callEmit)="childFunc($event)">Try it on component</a>

您的子组件html应该如下所示:

<a href='' (click)="onClick(val)"> </a>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM