gpt4 book ai didi

javascript - 无法为 Angular 中的超链接创建自定义点击指令

转载 作者:搜寻专家 更新时间:2023-10-30 21:25:36 24 4
gpt4 key购买 nike

我已按照 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>

demo 🔥🔥

关于javascript - 无法为 Angular 中的超链接创建自定义点击指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56752908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com