前端項目中常用到的指令彙總--持續更新

一、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綁定的屬性進行賦值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章