【问题标题】:How to subscribe to a parent Directive's EventEmitter emit?如何订阅父指令的 EventEmitter 发射?
【发布时间】:2022-09-22 21:42:14
【问题描述】:

我有一个第三方SortDirective,我正在扩展:

export declare class SortDirective implements CanDisable, HasInitialized, OnInit, OnChanges, OnDestroy {
    readonly sortChange: EventEmitter<Sort[]>;
    ....
}

@Directive({
  selector: \'[customSort]\'
})
export class AbxCustomSortDirective extends SortDirective implements OnInit {
    ....
}

我不知道如何订阅 SortDirective sortChange 发射?关键是我不知道SortDirective sortChange 在哪里发出。而且我认为我不应该。我唯一知道的是,一旦它发出,我想订阅它(并为我的组件订阅发出一些自定义事件)。

更新:这里是StackBlitz 的复制品。

  • 您是否在自定义指令中尝试过this.sortChange.subscribe()
  • @e-maggini 是的 - 它不会被解雇......但我注意到一个奇怪的事情:相同的基本指令(SortDirective)最初应用于表格组件本身和可排序的表格单元格标题(代表指令)...所以也许与此有关,我也需要将AbxCustomSortDirective 应用于标题单元格。不幸的是,不能共享代码 - 这个第 3 方组件是私有的......
  • 我仔细看了看:这不是细胞的问题。可能它与继承指令本身有关。我已经调试了代码,在基类中发出SortChange 后,继承类中的订阅没有反应。
  • @e-maggini 非常感谢!实际上,我没有扩展指令,而是添加了 \'modifier\' 指令。并解决了我的问题。请发表您的评论作为答案,我会接受。

标签: angular angular-directive angular-event-emitter


【解决方案1】:

我没有使用继承的指令逻辑(实际上不需要继承),而是使用建议的方法here 并解决了我的问题。

所以现在它看起来像这样:

@Directive({
  selector: '[extSortingPaging]'
})
export class AbxExtSortingPagingDirective {
  constructor(
    @Host() @Self() private tableComponent: TableComponent<any>,
    @Host() @Self() private sortDirective: SortDirective
  ) {
    this.sortDirective.sortChange.subscribe(() => {
      console.log('Sort changed!!!');
    });
  }
  ...
}

在组件中调用:

<bc-table
  sort
  extSortPage
  [extPaginator]="additionalFieldPaginator"
  [extDataSource]="measureLocationAdditionalFields.controls"
>

【讨论】:

    猜你喜欢
    • 2016-09-30
    • 2020-08-10
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多