我一直试图解决我的问题,但无济于事。
.html:
<li [myHighlight]="color" defaultColor="violet" routerLinkActive="active"><a [routerLink]="['user']">Users <span class="sr-only" >(current)</span></a></li>
指令:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[myHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) { }
@Input() defaultColor: string;
@Input('myHighlight') highlightColor: string;
@HostListener('mouseenter') onMouseEnter() {
this.highlight(this.highlightColor || this.defaultColor || 'red');
}
@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
应用程序模块:
import { PermissionsDirective, HighlightDirective } from "./shared/directives/permisions.directive";
@NgModule({
imports: [
..
],
declarations: [
..
HighlightDirective,
..
],
bootstrap: [
ApplicationComponent,
],
providers: [
..
]
})
export class AppModule { }
我收到的错误:
Can't bind to 'myHighlight' since it isn't a known property of 'li'.
我正在使用具有以下设置的 AOT 编译器:
{
"compilerOptions": {
"target": "es5",
"module": "es2015",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": true,
"noImplicitAny": false,
"suppressImplicitAnyIndexErrors": true,
"skipLibCheck": true,
"lib": [
"es2015",
"dom"
]
},
"files": [
.. all the good stuff ..
],
"angularCompilerOptions": {
"genDir": "aot",
"skipMetadataEmit": true
},
"compileOnSave": true,
"buildOnSave": true
}
我的猜测是,由于 AOT 编译器,我应该以与指南中不同的方式定义指令。 This是我用过的指南。我还观看了有关此的多元化类(class),但对其他人来说一切似乎都运行良好。有人能指出我正确的方向吗?如果我没有寻找几个小时,我就不会在这里......
编辑:为什么它认为“myHighlight”是“li”的属性,而“routerLinkActive”(我希望)是路由器指令的属性?
最佳答案
问题是我在主 application.module 中“声明”了该指令,而不是在使用它的指令中。我仍然不明白为什么每个模块都必须声明自己将使用的指令,而不是在主模块中声明一次。
关于angular - 无法绑定(bind)到 DIRECTIVE,因为它不是元素 Angular AOT 的已知属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45775979/