Search code examples
angularangular-directiveangular-event-emitter

How to subscribe to a parent Directive's EventEmitter emit?


I have a 3rd party SortDirective which I am extending:

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

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

I can't figure out how to subscribe to the SortDirective sortChange emit? The point is I don't know where in the SortDirective sortChange is emitted. And I don't think I should. The only thing I know is once it is emitted I want to subscribe to it (and emit some custom event for my component subscription).

UPDATE: here's the reproduction on StackBlitz.


Solution

  • Instead of fighting with the inherited directive logic (where an inheritance is actually not needed), I just used the approach suggested here and resolved my issue.

    So now it looks like this:

    @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!!!');
        });
      }
      ...
    }
    

    Called in the component:

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