diff --git a/components/select/option-item.component.ts b/components/select/option-item.component.ts index 8846297083a..9b0102c9e1f 100644 --- a/components/select/option-item.component.ts +++ b/components/select/option-item.component.ts @@ -6,25 +6,31 @@ import { ChangeDetectionStrategy, Component, + ElementRef, EventEmitter, Input, + NgZone, OnChanges, + OnInit, Output, SimpleChanges, TemplateRef, ViewEncapsulation } from '@angular/core'; +import { fromEvent } from 'rxjs'; +import { takeUntil } from 'rxjs/operators'; +import { NzDestroyService } from 'ng-zorro-antd/core/services'; import { NzSafeAny } from 'ng-zorro-antd/core/types'; @Component({ selector: 'nz-option-item', template: `
- {{ label }} - + - + + {{ label }}
@@ -38,12 +44,11 @@ import { NzSafeAny } from 'ng-zorro-antd/core/types'; '[class.ant-select-item-option-grouped]': 'grouped', '[class.ant-select-item-option-selected]': 'selected && !disabled', '[class.ant-select-item-option-disabled]': 'disabled', - '[class.ant-select-item-option-active]': 'activated && !disabled', - '(mouseenter)': 'onHostMouseEnter()', - '(click)': 'onHostClick()' - } + '[class.ant-select-item-option-active]': 'activated && !disabled' + }, + providers: [NzDestroyService] }) -export class NzOptionItemComponent implements OnChanges { +export class NzOptionItemComponent implements OnChanges, OnInit { selected = false; activated = false; @Input() grouped = false; @@ -60,18 +65,12 @@ export class NzOptionItemComponent implements OnChanges { @Output() readonly itemClick = new EventEmitter(); @Output() readonly itemHover = new EventEmitter(); - constructor() {} + constructor( + private elementRef: ElementRef, + private ngZone: NgZone, + private destroy$: NzDestroyService + ) {} - onHostMouseEnter(): void { - if (!this.disabled) { - this.itemHover.next(this.value); - } - } - onHostClick(): void { - if (!this.disabled) { - this.itemClick.next(this.value); - } - } ngOnChanges(changes: SimpleChanges): void { const { value, activatedValue, listOfSelectedValue } = changes; if (value || listOfSelectedValue) { @@ -81,4 +80,24 @@ export class NzOptionItemComponent implements OnChanges { this.activated = this.compareWith(this.activatedValue, this.value); } } + + ngOnInit(): void { + this.ngZone.runOutsideAngular(() => { + fromEvent(this.elementRef.nativeElement, 'click') + .pipe(takeUntil(this.destroy$)) + .subscribe(() => { + if (!this.disabled) { + this.ngZone.run(() => this.itemClick.emit(this.value)); + } + }); + + fromEvent(this.elementRef.nativeElement, 'mouseenter') + .pipe(takeUntil(this.destroy$)) + .subscribe(() => { + if (!this.disabled) { + this.ngZone.run(() => this.itemHover.emit(this.value)); + } + }); + }); + } }