简体   繁体   中英

Angular eventemitter not working when emitting the event from directive

appcomp.html

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

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

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

childcomp.ts

`

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

`

mydirective.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. Please let me know what is wrong here.

I think you most call callEmit on child component

childcomp.html

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

and in child Component emit the CallEmit Which called from appComp

childcomp.ts

@Output() callEmit = new EventEmitter();

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

and finally use

appCom.html

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

appcom.ts

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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