赞
踩
防抖公共文件
import { Directive, Input, OnDestroy, OnInit } from '@angular/core'; import { Subject } from 'rxjs'; import {debounceTime, takeUntil} from 'rxjs/operators'; @Directive({}) export abstract class AbstractDebounceDirective implements OnInit, OnDestroy { @Input() public debounceTime = 300; protected emitEvent$ = new Subject<Event>(); protected destroyed$ = new Subject<void>(); public ngOnInit(): void { this.emitEvent$ .pipe(debounceTime(this.debounceTime), takeUntil(this.destroyed$)) .subscribe((value) => this.emitValue(value)); } public abstract emitValue(event: Event): void; public ngOnDestroy(): void { this.destroyed$.next(); this.destroyed$.complete(); } }
点击防抖文件
import { Directive, EventEmitter, HostListener, Output } from '@angular/core'; import { AbstractDebounceDirective } from './abstract-debounce.directive'; @Directive({ selector: '[appDebounceClick]', }) export class DebounceClickDirective extends AbstractDebounceDirective { @Output() public debounceClick = new EventEmitter<Event>(); constructor() { super(); } @HostListener('click', ['$event']) public onClick(event: MouseEvent): void { event.preventDefault(); this.emitEvent$.next(event); } public emitValue(event: Event): void { this.debounceClick.emit(event); } }
输入防抖文件
import { Directive, EventEmitter, HostListener, Output } from '@angular/core'; import { AbstractDebounceDirective } from './abstract-debounce.directive'; @Directive({ selector: '[appDebounceInput]', }) export class DebounceInputDirective extends AbstractDebounceDirective { @Output() public debounceInput = new EventEmitter<Event>(); constructor() { super(); } @HostListener('keyup', ['$event']) public onClick(event: KeyboardEvent): void { // 这里的判断是用于回车搜索的输入框,如果需要输入实时搜索可将此判断去除 if (event.key === 'Enter') { event.preventDefault(); this.emitEvent$.next(event); } } public emitValue(event: KeyboardEvent): void { this.debounceInput.emit(event); } }
导出指令
import { NgModule } from '@angular/core'; import { DebounceClickDirective } from './debounce.directive'; import { DebounceInputDirective } from './debounceInput.directive'; @NgModule({ declarations: [ DebounceClickDirective, DebounceInputDirective ], exports: [ DebounceClickDirective, DebounceInputDirective ], }) export class SharedDirectivesModule { }
实际使用
<span (debounceClick)="export()" appDebounceClick [debounceTime]="300">导出模版</span>
<input (debounceClick)="enterSearch()" appDebounceClick [(ngModel)]="searchText" />
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。