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

标签 javascript angular typescript angular-directive

我已遵循 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/

相关文章:

javascript - 选择html表的一些行,并在单击链接时将所选行的一列的值发送到另一个php页面

javascript - 如果用户禁用了 JS,浏览器会下载 JS 文件吗?

javascript - 如何通过传递表单作为引用来获取复选框的值?

javascript - 在 Angular App 中通过 RouterLink 绑定(bind) URL 参数

node.js - 子模块中的 Angular 6 routerlink 和父模块中的 router-outlet (app.component)

javascript - 在 onclick 事件上调用另一个函数

angularjs - 在 Angular 2 中,当我尝试使用双向绑定(bind)时 ngIF 不起作用

angular - 与应用程序组件中的包进行通信的正确方法是什么?

angularjs - 使用 SystemJS 和 TypeScript 的 Angular 应用程序中的 "Unexpected token export"

javascript - InversifyJS - 注入(inject)对象的特定实例