Angular 防抖

不废话直接上代码

import {Directive, EventEmitter, HostListener, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {Subject, Subscription} from 'rxjs';
import {debounceTime} from 'rxjs/operators';

@Directive({
  selector: '[appDebounceClick]'
})
export class DebounceClickDirective implements OnInit, OnDestroy {
  @Input() debounceTime = 500;
  @Output() debounceClick = new EventEmitter();
  private clicks = new Subject<any>();
  private subscription: Subscription;
  constructor() { }
  ngOnInit() {
    this.subscription = this.clicks
      .pipe(debounceTime(this.debounceTime))
      .subscribe(e => this.debounceClick.emit(e));
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  @HostListener('click', ['$event'])
  clickEvent(event: MouseEvent) {
    event.preventDefault();
    event.stopPropagation();
    this.clicks.next(event);
  }
}

使用方式

在模板标签中添加 appDebounceClick 属性,默认500毫秒间隔,依据输入属性可自定义间隔时间,方式如下

<button
  type="submit"
  appDebounceClick
  (debounceClick)="confirmAddUser(registerData)"
  [debounceTime]="300"
>
  确认
</button>
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Angular 中,防抖(debounce)是一种用于控制函数执行频率的技术。它可以限制函数在连续触发时的执行次数,减少不必要的计算和网络请求。 要在 Angular 中实现防抖,你可以使用 RxJS 库提供的 `debounceTime` 操作符。RxJS 是 Angular 中常用的响应式编程库。 首先,确保你已经在项目中引入了 RxJS。你可以通过以下方式导入 `debounceTime`: ```typescript import { debounceTime } from 'rxjs/operators'; ``` 然后,在需要应用防抖的地方,将 `debounceTime` 操作符应用于触发函数的 Observable。 假设你有一个触发搜索的输入框,并且你希望等待用户停止输入一段时间后再触发搜索函数。你可以使用以下代码实现防抖: ```typescript import { Component } from '@angular/core'; import { Subject } from 'rxjs'; import { debounceTime } from 'rxjs/operators'; @Component({ selector: 'app-search', template: ` <input (input)="handleSearch($event.target.value)" /> ` }) export class SearchComponent { searchSubject = new Subject<string>(); constructor() { this.searchSubject.pipe( debounceTime(300) // 设置防抖时间为300ms ).subscribe((value) => { // 在这里执行搜索逻辑 console.log('Searching for:', value); }); } handleSearch(value: string) { this.searchSubject.next(value); } } ``` 在上述代码中,`searchSubject` 是一个 Subject,它负责接收输入框的值。通过使用 `debounceTime` 操作符,并设置防抖时间为300毫秒,确保搜索函数在用户停止输入300毫秒后才会执行。 当用户输入时,`handleSearch` 方法会将输入值发送给 `searchSubject`。然后,`searchSubject` 会触发防抖逻辑,等待300毫秒后,调用 `subscribe` 中的回调函数进行搜索操作。 这样,就实现了在 Angular 中使用防抖的功能。希望对你有所帮助!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值