2017-07-02 81 views
0

我想根据视频教程使用简单的指令。我不知道为什么,我的代码不会影响文本颜色。有人能帮助我吗?这里是代码: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'; 
    } 

} 

回答

2

一个指令不一项服务。你不能把它作为提供者注入。你需要在模块中和你的组件一起声明它。

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

查看Plunker sample说明了这一点。