[英]Cannot create a custom click Directive for Hyperlink in Angular
我已按照在Angular中創建自定義防抖動Click指令中提到的所有步驟進行操作,並嘗試將此自定義指令用於超鏈接,如下所示:
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'的已知屬性”錯誤。 我是否需要在指令中定義自定義點擊事件? 如果可以,怎么辦?
如果您在與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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.