Angular 6 指令错误 - 无法绑定到"appClickEvent",因为它不是 'button' 的已知属性



创建了一个模块,其中包含一个指令,该指令将从按钮捕获单击事件。

click.directive.ts

import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appClickEvent]'
})
export class ClickDirective {
private el:any;
constructor(
private elem: ElementRef,
) {}
@Input() appClickEvent: any;
@HostListener('click', ['$event']) clickEvent(event:any) {
console.log(this.appClickEvent) // {label: 'Foo'}
}
}

组件中的用法

我想{label: 'Foo'}获取数据并将其传递给click.directive.ts中的@HostListener

<button [appClickEvent]="{label: 'Foo'}">Click Foo</button>

my.module.ts

import { CommonModule } from '@angular/common';
import { ClickDirective } from './click.directive';
@NgModule({
imports: [
CommonModule
],
exports: [
ClickDirective
],
declarations: [
ClickDirective
]
})
@NgModule()
export class McAnalyticsModule {}

app.module.ts

// ... other modules
import { MyModule } from '@app/my/my.module';
@NgModule({
imports: [
// .. .other modules
MyModule,
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }

错误

无法绑定到"appClickEvent",因为它不是"按钮"的已知属性。("][appClickEvent]="{label: 'Foo'}">Foo"(

工作示例

click.directive.ts:

import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appClickEvent]'
})
export class ClickDirective {
private el:any;
constructor(
private elem: ElementRef,
) {}
@Input() appClickEvent: any;
@HostListener('click', ['$event']) clickEvent(event:any) {
console.log("your output");
console.log(this.appClickEvent)
}
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { ClickDirective } from './click.directive';
@NgModule({
imports:      [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent,ClickDirective ], exports: [ClickDirective],
bootstrap:    [ AppComponent ]
})
export class AppModule { }

.html:

<button appClickEvent="{label: 'Foo'}">Click Foo</button>

您应该在app.module.tsNotMyModule中注入McAnalyticsModule。所以棱角没有找到McAnalyticsModule.

app.module.ts中包含McAnalyticsModule,如下所示:

import { McAnalyticsModule } from '@app/my/my.module';     //<== Remove MyModule class 
@NgModule({
imports: [
// .. .other modules
McAnalyticsModule,          //<== Remove MyModule class 
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }

这是工作示例:Angular 6

指令

最新更新