簡體   English   中英

Angular2指令不起作用

[英]Angular2 directive not working

我正在嘗試根據視頻教程使用一個簡單的指令。 我不知道為什么,我的代碼不影響文本顏色。 有人可以幫我嗎? 這是代碼:

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示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM