I am trying to create a simple directive in Angular 2 which highlights the content inside an html element.
Here is my code:
main.ts
import {bootstrap} from '@angular/platform-browser-dynamic';
import {Component} from '@angular/core';
import {HighLightCmp} from "./highlight.component";
@Component({
selector: 'app',
template: `
<div highlight>
Highlight me.
</div>
`,
directives: [HighLightCmp]
})
class AppCmp{
constructor(){}
}
bootstrap(AppCmp);
highlight.component.ts
import {ElementRef,Renderer,Directive,OnInit} from "@angular/core";
@Directive({
selector: "[highlight]"
})
export class HighLightCmp implements OnInit{
private color: "green";
constructor(private _elRef:ElementRef,private _renderer:Renderer){}
ngOnInit(){
this._renderer.setElementStyle(this._elRef,"background-color",this.color);
}
}
But I am getting the following exception while running
EXCEPTION: TypeError: Cannot set property 'background-color' of undefined
I re-produced the problem here on plunker
You can see the error message in the console. Any thoughts?
Thanks in anticipation.