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:
Can anyone find what I'm doing wrong?
Thanks.
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)
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With