Error _renderer.setElementStyle "Cannot set property" background-color "from undefined to [null]"

I study angular2 in the udemy course for angular2 , and the teacher wrote a directive that highlights the html element.

I try to do this as steam, but for me this is an exception _renderer.setElementStyle .

EXCEPTION: TypeError: cannot set property "background-color" of undefined to [null]

Directive:

 import {Directive, ElementRef, Renderer, OnInit} from 'angular2/core'; @Directive({ selector: '[highlight-directive]' }) export class HighlightDirective implements OnInit{ private _defaultColor= 'green'; constructor(private _elmRef: ElementRef, private _renderer: Renderer) {} ngOnInit(): any { this._renderer.setElementStyle(this._elmRef, "background-color", this._defaultColor); //this._elmRef.nativeElement.style.backgroundColor = this._defaultColor; //this way works fine. } } 

Tab. That I use the directive:

 template: ` <div highlight-directive> Highlight me </div> <br> <div highlight-directive> 2 Highlight me 2 </div> `, 

Teacher work area: enter image description here

Can someone find what I'm doing wrong?

Thanks.

+6
source share
4 answers

As suggested by @NirSchwartz

Since beta.1 Renderer no longer accepts ElementRef , but nativeElement , so your Renderer line adding background color should look like this:

 this._renderer.setElementStyle(this._elmRef.nativeElement, "background-color", this._defaultColor); 

You can check all these changes in CHANGELOG . In particular, in your case, you should check the beta.1 change log (change section)

+18
source

Look at line 10 of the teacher’s workspace:
private _defaultColor:'red'; //does not work;
private _defaultColor ='red'; //Job;
and of course use the expression
this._renderer.setElementStyle(this._elmRef.nativeElement, "background-color", this._defaultColor);
on line 16

+2
source

The answer is not for me, I had to change

  private _defaultColor :'green'; 

to

  private _defaultColor ='green'; 

I also realized what changed and worked

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

to

  this._renderer.setElementStyle(this._elRef.nativeElement, 'background-color', 'green'); 

I still don’t know why

+1
source
 private _defaultColor :'green'; this._renderer.setElementStyle(this._elRef.nativeElement, 'background-color', this._defaultColor); 

This does not work because you never set the VALUE value of the _defaultColor property. Remember that the part after the colon in TypeScript matches the TYPE property, not the value. For example (and be a pointer to indicating the type of a variable):

 private _defaultColor: string = 'green'; 

This works fine (and I personally prefer to use this syntax, although without it the default property will contain a string).

0
source

All Articles