Angular2 Renderer setElementStyle不起作用

时间:2016-08-18 16:30:32

标签: angular

这是我的组件元数据:

@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);
   }
}

收到错误:&#34;无法设置属性&#39; background-color&#39;未定义&#34;。

1 个答案:

答案 0 :(得分:6)

问题是你传递的不是原生元素。试试这个:

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