首页 > 解决方案 > 在角度指令中定义 @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');
  }
}

标签: angular

解决方案


使您的@Output parameter异步,这将在下一次滴答时调用父函数,因此将调用您的指令单击

  @Output() proceedToDetailView = new EventEmitter(true); // this will change from sync to async

推荐阅读