无法为 Angular 中的超链接创建自定义点击指令
Cannot create a custom click Directive for Hyperlink in Angular
我已按照 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' 的已知 属性” 错误。我是否需要在指令中定义自定义点击事件?如果是这样怎么办?
如果您在与 app.module 不同的模块中创建指令,您还需要将指令 class 添加到该模块装饰器的导出部分,这将确保它可以在模块外部访问
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ DebounceClickDirective ],
exports:[ DebounceClickDirective ], //
})
export class CustomesModule { }
app.template.html
<a appDebounceClick (debounceClick)="delete()" [debounceTime]="700" >click me </a>
我已按照 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' 的已知 属性” 错误。我是否需要在指令中定义自定义点击事件?如果是这样怎么办?
如果您在与 app.module 不同的模块中创建指令,您还需要将指令 class 添加到该模块装饰器的导出部分,这将确保它可以在模块外部访问
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ DebounceClickDirective ],
exports:[ DebounceClickDirective ], //
})
export class CustomesModule { }
app.template.html
<a appDebounceClick (debounceClick)="delete()" [debounceTime]="700" >click me </a>