Skip to content

Commit

Permalink
fix(module:button): prevent default event fire (#7267)
Browse files Browse the repository at this point in the history
* fix(module:button): prevent default event fire

* test(module:button): add test case

* test(module:button): update test logic

* test(module:button): revert test case name

* chore(module:button): resolve test case fail
  • Loading branch information
chenc041 committed Feb 21, 2022
1 parent f972391 commit 2306e0d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
4 changes: 2 additions & 2 deletions components/button/button.component.ts
Expand Up @@ -141,10 +141,10 @@ export class NzButtonComponent implements OnDestroy, OnChanges, AfterViewInit, A
// The compiler generates the `ɵɵlistener` instruction which wraps the actual listener internally into the
// function, which runs `markDirty()` before running the actual listener (the decorated class method).
// Since we're preventing the default behavior and stopping event propagation this doesn't require Angular to run the change detection.
fromEvent<MouseEvent>(this.elementRef.nativeElement, 'click')
fromEvent<MouseEvent>(this.elementRef.nativeElement, 'click', { capture: true })
.pipe(takeUntil(this.destroy$))
.subscribe(event => {
if (this.disabled && (event.target as HTMLElement)?.tagName === 'A') {
if ((this.disabled && (event.target as HTMLElement)?.tagName === 'A') || this.nzLoading) {
event.preventDefault();
event.stopImmediatePropagation();
}
Expand Down
18 changes: 18 additions & 0 deletions components/button/button.spec.ts
Expand Up @@ -180,6 +180,17 @@ describe('button', () => {
// Previously, it would've caused `tick()` to be called 2 times, because 2 click events have been triggered.
expect(spy).toHaveBeenCalledTimes(0);
});

it('prevent default and stop propagation when the button state is loading', fakeAsync(() => {
testBed.component.nzLoading = true;
testBed.fixture.detectChanges();
const event = new MouseEvent('click');
const preventDefaultSpy = spyOn(event, 'preventDefault').and.callThrough();
const stopImmediatePropagationSpy = spyOn(event, 'stopImmediatePropagation').and.callThrough();
buttonElement.dispatchEvent(event);
expect(preventDefaultSpy).toHaveBeenCalledTimes(1);
expect(stopImmediatePropagationSpy).toHaveBeenCalledTimes(1);
}));
});
});

Expand Down Expand Up @@ -281,6 +292,13 @@ export class TestButtonIconOnlyComponent {}
})
export class TestButtonIconOnlyLoadingComponent {}

@Component({
template: `<button nz-button [nzLoading]="nzLoading" (click)="buttonClick()">click me</button> `
})
export class TestButtonWithLoadingComponent {
@Input() nzLoading: boolean = false;
}

@Component({
template: `
<div [dir]="direction">
Expand Down

0 comments on commit 2306e0d

Please sign in to comment.