這是我的組件元數據: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);
}
}
它得到的錯誤:「無法設置屬性‘背景顏色’未定義」。
順便說一下,這條線路正在工作。 'this._elRef.nativeElement.style.backgroundColor = this.customColor || this._defaultColor;' –
@#$#!停止使用私人財產的下劃線! :) https://angular.io/styleguide#03-04 –
試過了。不起作用。 –