Angular2 Renderer setElementStyle无法正常工作 [英] Angular2 Renderer setElementStyle is not working

查看:267
本文介绍了Angular2 Renderer setElementStyle无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的组件元数据:

@Component({
   moduleId: module.id,
   selector: 'si-attribute-directive',
   template: `
      <div myHighlight [customColor]="'red'">Highlight Me..</div>
      <br>
      <div myHighlight>Highlight Me Too..</div>
   `,
   directives: [MyHighlightDirective]
})

这是我的指令:

import { Directive, ElementRef, OnInit, Renderer, Input } from '@angular/core';

@Directive({
    selector: '[myHighlight]'
})
export class MyHighlightDirective implements OnInit {
   private _defaultColor : string = "green";
   @Input() customColor:string;
   constructor(private _elRef:ElementRef, private _renderer:Renderer) { }

   ngOnInit():any {
       this._renderer.setElementStyle(this._elRef, 'background-color', this.customColor || this._defaultColor);
   }
}

正在收到错误:无法设置未定义的属性'background-color'."

It's getting the error: "Cannot set property 'background-color' of undefined".

推荐答案

问题是您传递的不是本机元素.试试这个:

The problem is that you pass not native element. Try this:

this._renderer.setElementStyle(this._elRef.nativeElement, 'background-color', this.customColor || this._defaultColor);

这篇关于Angular2 Renderer setElementStyle无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆