Skip to content

Commit 2306e0d

Browse files
authored
fix(module:button): prevent default event fire (#7267)
* 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
1 parent f972391 commit 2306e0d

2 files changed

Lines changed: 20 additions & 2 deletions

File tree

components/button/button.component.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,10 +141,10 @@ export class NzButtonComponent implements OnDestroy, OnChanges, AfterViewInit, A
141141
// The compiler generates the `ɵɵlistener` instruction which wraps the actual listener internally into the
142142
// function, which runs `markDirty()` before running the actual listener (the decorated class method).
143143
// Since we're preventing the default behavior and stopping event propagation this doesn't require Angular to run the change detection.
144-
fromEvent<MouseEvent>(this.elementRef.nativeElement, 'click')
144+
fromEvent<MouseEvent>(this.elementRef.nativeElement, 'click', { capture: true })
145145
.pipe(takeUntil(this.destroy$))
146146
.subscribe(event => {
147-
if (this.disabled && (event.target as HTMLElement)?.tagName === 'A') {
147+
if ((this.disabled && (event.target as HTMLElement)?.tagName === 'A') || this.nzLoading) {
148148
event.preventDefault();
149149
event.stopImmediatePropagation();
150150
}

components/button/button.spec.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,17 @@ describe('button', () => {
180180
// Previously, it would've caused `tick()` to be called 2 times, because 2 click events have been triggered.
181181
expect(spy).toHaveBeenCalledTimes(0);
182182
});
183+
184+
it('prevent default and stop propagation when the button state is loading', fakeAsync(() => {
185+
testBed.component.nzLoading = true;
186+
testBed.fixture.detectChanges();
187+
const event = new MouseEvent('click');
188+
const preventDefaultSpy = spyOn(event, 'preventDefault').and.callThrough();
189+
const stopImmediatePropagationSpy = spyOn(event, 'stopImmediatePropagation').and.callThrough();
190+
buttonElement.dispatchEvent(event);
191+
expect(preventDefaultSpy).toHaveBeenCalledTimes(1);
192+
expect(stopImmediatePropagationSpy).toHaveBeenCalledTimes(1);
193+
}));
183194
});
184195
});
185196

@@ -281,6 +292,13 @@ export class TestButtonIconOnlyComponent {}
281292
})
282293
export class TestButtonIconOnlyLoadingComponent {}
283294

295+
@Component({
296+
template: `<button nz-button [nzLoading]="nzLoading" (click)="buttonClick()">click me</button> `
297+
})
298+
export class TestButtonWithLoadingComponent {
299+
@Input() nzLoading: boolean = false;
300+
}
301+
284302
@Component({
285303
template: `
286304
<div [dir]="direction">

0 commit comments

Comments
 (0)