前端项目中常用到的指令汇总--持续更新

一、button中的点击事件节流

需求:避免用户在持续单击按钮的时候不断触发绑定的函数调用,节约资源。

方法:通过指令的方式赋予button新的click行为特定。

注意:采用订阅的方式要注意在销毁的时候及时取消订阅。

大致流程如下

1、创建指令

2、@HostListener中监听click事件,并将事件作为observable发出

3、订阅发出的click事件,并且debounceTime一段时间

4、再将事件emit,让button中绑定的事件执行

5、destroy的时候取消订阅

代码如下:

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

@Directive({
  selector: '[appDebounce]'
})
export class DebounceDirective {
  click = new Subject<any>(); // 将事件发出
  clickSubscription: Subscription; // 便于取消订阅
  @Output() clickDebounce = new EventEmitter(); // emit事件对象
  constructor() {
    console.log('debounceClick init');
    this.clickSubscription = this.click.pipe(
      debounceTime(2000),
      //throttleTime(2000),
    ).subscribe(
      event => {
        this.clickDebounce.emit(event);
      }
    )
   }

  @HostListener('click',["$event"])
  clickEvent(e: MouseEvent){
    e.preventDefault();
    e.stopPropagation();
    console.log('debounce click');
    this.click.next(e);
  }

  ngOnDestroy(){
    this.clickSubscription.unsubscribe();
  }
}

使用如下:

<button appDebounce (clickDebounce)="debounceClick('a')">debounceClick指令</button>

二、图片无法加载显示默认图片

需求:当图片地址未获取到时,显示默认图片;当图片地址加载404等其他错误时,显示默认图片

方法:获取图片的src地址,当为空的时候,显示默认图片;指令绑定error函数,当该事件触发的时候将图片的src设置为默认图片。

这个应用相对简单,代码如下

import { Directive, Host, HostListener, ElementRef } from '@angular/core';

@Directive({
  selector: '[appErrorImg]'
})
export class ErrorImgDirective {

  constructor(
    public imgElem: ElementRef
  ) { }

  @HostListener('error' ,['$event.target'])
  errorImage(ele ){
    this.imgElem.nativeElement.src = "./assets/test.png"
  }

}

以上默认图片的路径也可以自定义,通过input绑定的属性进行赋值。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值