我已经遵循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中进行了必要的导入定义。但是在调试它时,我遇到“ 无法绑定到'debounceTime',因为它不是'a'的已知属性” 错误。我是否需要在指令中定义自定义点击事件?如果可以,怎么办?
答案 0 :(得分:3)
如果您在与app.module不同的模块中创建指令,则还需要将指令类添加到该模块装饰器的exports部分,这将确保在模块外部可以访问
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ DebounceClickDirective ],
exports:[ DebounceClickDirective ], // ?
})
export class CustomesModule { }
app.template.html
<a appDebounceClick (debounceClick)="delete()" [debounceTime]="700" >click me ? </a>