2016-08-18 112 views
0

這是我的組件元數據:Angular2渲染setElementStyle不工作

@Component({ 
    moduleId: module.id, 
    selector: 'si-attribute-directive', 
    template: ` 
     <div myHighlight [customColor]="'red'">Highlight Me..</div> 
     <br> 
     <div myHighlight>Highlight Me Too..</div> 
    `, 
    directives: [MyHighlightDirective] 
}) 

這是我的指令:

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

@Directive({ 
    selector: '[myHighlight]' 
}) 
export class MyHighlightDirective implements OnInit { 
    private _defaultColor : string = "green"; 
    @Input() customColor:string; 
    constructor(private _elRef:ElementRef, private _renderer:Renderer) { } 

    ngOnInit():any { 
     this._renderer.setElementStyle(this._elRef, 'background-color', this.customColor || this._defaultColor); 
    } 
} 

它得到的錯誤:「無法設置屬性‘背景顏色’未定義」。

+0

順便說一下,這條線路正在工作。 'this._elRef.nativeElement.style.backgroundColor = this.customColor || this._defaultColor;' –

+2

@#$#!停止使用私人財產的下劃線! :) https://angular.io/styleguide#03-04 –

+0

試過了。不起作用。 –

回答

6

問題是你傳遞的不是本地元素。試試這個:

this._renderer.setElementStyle(this._elRef.nativeElement, 'background-color', this.customColor || this._defaultColor); 
+0

不起作用... –

+0

@ H.Jabi更新了我的答案。 –

+0

好的,這個炒鍋。謝謝。 –