javascript - 从指令发出事件时,角度事件发射器不起作用
问题描述
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'
})
`
我的指令.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,但无法完成这项工作。请让我知道这里有什么问题。
解决方案
我认为您最常在子组件上调用 callEmit
childcomp.html
<a href='' [mydirective]="val" (callEmit)="childFunc($event)"> </a>
并在子组件中发出从 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)
}
推荐阅读
- excel - 如何填写excel中的列值?
- python - 找出给定N个数中K的倍数
- python - 在 python 脚本中运行 setenv linux 命令
- hibernate - 休眠OneToMany关系无法获得孩子
- django - Django CSRF 和 axios 发布 403 Forbidden
- csv - 参数化平面文件连接字符串
- c++ - Boost.Log - 管理重复的连续日志消息并防止打印重复
- node.js - 使用 Google App Engine 部署两个应用程序
- laravel - 如何在另一个中间件 Laravel 中有条件地添加中间件
- python - Python tabula-py 的问题,错误“未知位置”