我已遵循 Creating a Custom Debounce Click Directive in Angular 上提到的所有步骤并尝试将此自定义指令用于超链接,如下所示:
directive.ts:
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();
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) {
event.preventDefault();
event.stopPropagation();
this.clicks.next(event);
}
}
.html:
<a appDebounceClick (debounceClick)="delete()" [debounceTime]="700"></a>
我还在 app.module.ts 和 my-component.ts 中进行了必要的导入定义。但是在调试它时,我遇到“无法绑定(bind)到'debounceTime',因为它不是'a'的已知属性”错误。我需要在指令中定义自定义点击事件吗?如果是这样怎么办?
最佳答案
如果您在与 app.module 不同的模块中创建指令,您还需要将指令类添加到该模块装饰器的导出部分,这将确保它可以在模块外部访问
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ DebounceClickDirective ],
exports:[ DebounceClickDirective ], // 👈
})
export class CustomesModule { }
app.template.html
<a appDebounceClick (debounceClick)="delete()" [debounceTime]="700" >click me 🎯 </a>
关于javascript - 无法在 Angular 中为超链接创建自定义单击指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56752908/