我正在为Angle2在
udemy课程中研究angular2,老师写了一个突出显示html元素的指令.
我试图做休闲,但对我来说_renderer.setElementStyle抛出异常.
EXCEPTION: TypeError: Cannot set property ‘background-color’ of
undefined in [null]
指令:
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. } }
我使用该指令的模板:
template: ` <div highlight-directive> Highlight me </div> <br> <div highlight-directive> 2 Highlight me 2 </div> `,
任何人都能找到我做错的事吗?
谢谢.