一、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绑定的属性进行赋值。