我正在 udemy 学习 angular2 angular2 的类(class),老师写了一个突出显示 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>
`,
谁能发现我做错了什么?
谢谢。
最佳答案
根据@NirSchwartz 的建议
由于 beta.1 渲染器不再采用 ElementRef
,而是采用 nativeElement
,因此添加背景色的渲染器行应该如下所示
this._renderer.setElementStyle(this._elmRef.nativeElement, "background-color", this._defaultColor);
您可以在他们的 CHANGELOG 中查看所有这些更改.具体针对您的情况,您应该检查 beta.1 的更新日志(重大更改部分)
关于html - [null] 中未定义的错误 _renderer.setElementStyle "Cannot set property ' 背景颜色',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35536964/