从指令发出事件时,角度事件发射器不起作用

时间:2019-07-31 05:57:04

标签: javascript angular dom eventemitter

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

` 在上面的代码中,我试图使用eventemitter从appcomp调用parentFunc,但无法完成这项工作。请让我知道这里出了什么问题。

2 个答案:

答案 0 :(得分:1)

我认为您最常在子组件上调用callEmit

childcomp.html

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

并在子Component中发出从appComp调用的CallEmit

childcomp.ts

@Output() callEmit = new EventEmitter();

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

最后使用

appCom.html

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

appcom.ts

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

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

答案 1 :(得分:-1)

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

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