Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error _renderer.setElementStyle "Cannot set property 'background-color' of undefined in [null]"

I'm studding angular2 at the udemy course for angular2, and the teacher wrote a directive that highlight a html element.

I trying to do as fallow but the to me the _renderer.setElementStyle throws exception.

EXCEPTION: TypeError: Cannot set property 'background-color' of undefined in [null]

The 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.
    }
}

The tamplate that I use the directive:

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

The teacher workspace: enter image description here

Can anyone find what I'm doing wrong?

Thanks.

like image 534
Nir Schwartz Avatar asked Feb 21 '16 13:02

Nir Schwartz


3 Answers

As suggested by @NirSchwartz

Since beta.1 Renderer doesn't take an ElementRef anymore, but a nativeElement, so your Renderer line adding the background color should look like this

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

You can check all these changes in their CHANGELOG. Specifically to your case you should check the changelog for beta.1 (breaking changes section)

like image 104
Eric Martinez Avatar answered Nov 15 '22 17:11

Eric Martinez


look at line 10 of The teacher workspace:
private _defaultColor:'red'; //doesn't work;
private _defaultColor ='red'; // work;
and of course use expression
this._renderer.setElementStyle(this._elmRef.nativeElement, "background-color", this._defaultColor);
in line 16

like image 23
TJQKAs Avatar answered Nov 15 '22 18:11

TJQKAs


The answer provided did not work for me I had to change

 private _defaultColor :'green';

to

 private _defaultColor ='green';

I also realized changing the following also 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

like image 2
Lawrence Macharia Avatar answered Nov 15 '22 19:11

Lawrence Macharia