我想创建一个指令,当用户单击按钮时要求进行确认。为此,我应该能够存储原始事件,并且仅在用户确认选择后才调用它。
我在这里嘲笑了类似的行为:
https://stackblitz.com/edit/angular-6wnvjk?file=src%2Fapp%2Fapp.component.html
(这是超时,而不是确认,但问题是相同的)
如何存储原始事件,然后在超时/确认结束后调用它?
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[confirm]'
})
export class ConfirmDirective {
constructor() { }
@HostListener('click', ['$event'])
onClick(event: MouseEvent) {
console.log('handler from directive');
// 1 - Would like to store original event
const originalEvent = () => {};
// Would like to call it later
setTimeout(() => {
originalEvent();
})
}
}
答案 0 :(得分:2)
您可以构建指令以拦截点击并仅在条件通过时发出它们:
@Directive({
selector: '[confirm]',
})
export class ConfirmDirective implements OnInit, OnDestroy {
@Output() confirmed = new EventEmitter();
private clicks = new Subject();
private subscription: Subscription;
constructor() {}
ngOnInit() {
this.subscription = this.clicks
.pipe(
switchMap((event) =>
confirm('Do you agree?') ? of(event) : null
)
)
.subscribe((e) => this.confirmed.emit(e));
}
ngOnDestroy() {
if (this.subscription) this.subscription.unsubscribe();
}
@HostListener('click', ['$event'])
clickEvent(event) {
event.preventDefault();
event.stopPropagation();
this.clicks.next(event);
}
}
用法:
<button confirm (confirmed)="doSomething()">Click</button>
祝你好运!