angular - 在角度指令中定义 @HostListener 事件的事件顺序
问题描述
我有一个 Angular 9 应用程序,其父组件包含一个包含按钮的子组件(我们称之为“概述”)。单击按钮时,子组件会发出一个事件,该事件被父组件捕获,以将子组件替换为另一个组件(我们称之为“细节”)。
“overview”组件中的按钮有一个带有@HostListener
捕获按钮点击的指令。我的问题是这个监听器永远不会被执行,因为显然,当子组件被替换时,Angular 不会等待指令中的点击监听器被执行。
有没有办法强制 Angular在组件本身中定义的点击监听器之前@HostListener
执行使用on 指令定义的点击监听器?
示例代码:
父组件
<!-- parent.component.html -->
<div>
<overview *ngIf="currentStep == cardStep.OVERVIEW"
(proceedToDetailView)="currentStep = cardStep.DETAIL"
></overview>
<detail *ngIf="currentStep == cardStep.DETAIL"></detail>
</div>
// parent.component.ts
export enum CardStep {
OVERVIEW = 'OVERVIEW',
DETAIL= 'DETAIL',
}
@Component({
selector: 'parent',
templateUrl: './parent.component.html',
})
export class ParentComponent {
currentStep = CardStep.OVERVIEW;
cardStep = CardStep;
}
概览组件
<!-- overview.component.html -->
<div>
<button myDirective
(click)="proceedToDetail()"
></button>
</div>
// overview.component.ts
@Component({
selector: 'overview',
templateUrl: './overview.component.html',
})
export class OverviewComponent{
@Output() proceedToDetailView = new EventEmitter();
proceedToDetail(): void {
this.proceedToDetailView.emit();
}
}
指示
// my.directive.ts
@Directive({
selector: '[myDirective]'
})
export class MyDirective {
@HostListener('click', ['$event'])
handleEvent(event): void {
console.log('this should be executed, but isn't');
}
}
解决方案
使您的@Output parameter
异步,这将在下一次滴答时调用父函数,因此将调用您的指令单击
@Output() proceedToDetailView = new EventEmitter(true); // this will change from sync to async
推荐阅读
- python - np.float64 和 python float (64) 中的精度差异
- elasticsearch - Metricbeat 没有找到任何 application_pool
- kubernetes - Helm 预安装作业在服务帐户之前创建
- ios - 从 Firebase 实时数据库中获取需要几秒钟 [已修改]
- php - Slim Php v3 查询字符串
- javascript - HERE 映射 javascript API 多个航点
- r - 如果所有值都是特定值,则删除一列
- c# - 对于 AddModulesAsync (C# Discord.Net),我没有正确的论据
- python - python - 如何在python暂停期间检测到按下的键?
- javascript - WebpackError:ReferenceError:Gatsby 上未定义窗口