Angular2指令不起作用



我正在尝试根据视频教程使用一个简单的指令。我不知道为什么,我的代码不会影响文本颜色。有人可以帮助我吗?代码如下:

app.component.html:

<p colorer>textTMP</p>

app.component.ts:

import { Colorer } from './colorer.service';

@Component({
selector: 'app-component',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
providers: [ Colorer],
})
export class AppComponent{}

colorer.service.ts:

import { Input, Directive, HostListener, ElementRef } from '@angular/core';

@Directive({
selector: '[colorer]',
host: {
'(mouseenter)': 'color()'
}
})
export class Colorer {
constructor(private _el: ElementRef) {}
color() {
this._el.nativeElement.style.color = 'red';
}
}

指令不是服务。不能将其作为提供程序注入。您需要在模块中与组件一起声明它。

@NgModule({
imports: [
BrowserModule
],
declarations: [ AppComponent, Colorer ],
bootstrap: [ AppComponent ]
})
export class AppModule {}

请参阅说明这一点的 Plunker 示例。

最新更新