diff --git a/npm/ng-packs/packages/core/src/lib/directives/stop-propagation.directive.ts b/npm/ng-packs/packages/core/src/lib/directives/stop-propagation.directive.ts index 7b9ae46e9c..16fc6e47d3 100644 --- a/npm/ng-packs/packages/core/src/lib/directives/stop-propagation.directive.ts +++ b/npm/ng-packs/packages/core/src/lib/directives/stop-propagation.directive.ts @@ -1,15 +1,15 @@ -import { Directive, ElementRef, EventEmitter, OnInit, Output, Renderer2 } from '@angular/core'; +import { Directive, ElementRef, EventEmitter, OnInit, Output, Renderer2, OnDestroy } from '@angular/core'; import { fromEvent } from 'rxjs'; import { takeUntilDestroy } from '@ngx-validate/core'; @Directive({ // tslint:disable-next-line: directive-selector - selector: '[click.stop]' + selector: '[click.stop]', }) -export class ClickEventStopPropagationDirective implements OnInit { +export class ClickEventStopPropagationDirective implements OnInit, OnDestroy { @Output('click.stop') readonly stopPropEvent = new EventEmitter(); - constructor(private renderer: Renderer2, private el: ElementRef) {} + constructor(private el: ElementRef) {} ngOnInit(): void { fromEvent(this.el.nativeElement, 'click') @@ -19,4 +19,6 @@ export class ClickEventStopPropagationDirective implements OnInit { this.stopPropEvent.emit(event); }); } + + ngOnDestroy(): void {} } diff --git a/npm/ng-packs/packages/core/src/lib/tests/stop-propagation.directive.spec.ts b/npm/ng-packs/packages/core/src/lib/tests/stop-propagation.directive.spec.ts new file mode 100644 index 0000000000..678025572e --- /dev/null +++ b/npm/ng-packs/packages/core/src/lib/tests/stop-propagation.directive.spec.ts @@ -0,0 +1,40 @@ +import { createDirectiveFactory, SpectatorDirective } from '@ngneat/spectator/jest'; +import { ClickEventStopPropagationDirective } from '../directives/stop-propagation.directive'; + +describe('ClickEventStopPropagationDirective', () => { + let spectator: SpectatorDirective; + let directive: ClickEventStopPropagationDirective; + let link: HTMLAnchorElement; + let childClickEventFn = jest.fn(() => null); + let parentClickEventFn = jest.fn(() => null); + const createDirective = createDirectiveFactory({ + directive: ClickEventStopPropagationDirective, + }); + + beforeEach(() => { + spectator = createDirective( + '
Link
', + { + hostProps: { parentClickEventFn, childClickEventFn }, + }, + ); + directive = spectator.directive; + link = spectator.query('a'); + childClickEventFn.mockClear(); + parentClickEventFn.mockClear(); + }); + + test('should be created', () => { + spectator.click('a'); + expect(directive).toBeTruthy(); + }); + + test("should not call click event of parent when child element's click event is triggered", done => { + spectator.setHostInput({ parentClickEventFn, childClickEventFn }); + spectator.click('a'); + spectator.detectChanges(); + expect(childClickEventFn).toHaveBeenCalled(); + expect(parentClickEventFn).not.toHaveBeenCalled(); + done(); + }); +});