42547

Angular2 Renderer setElementStyle is not working

Question:

This is my component metadata:

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

And this is my directive:

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

It's getting the error: "Cannot set property 'background-color' of undefined".

Answer1:

The problem is that you pass not native element. Try this:

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

Recommend