Angular 4 @HostBinding绑定到样式prop

时间:2018-03-10 18:56:32

标签: angular

我试图用指令

绑定到ele的样式道具



import {Directive, OnInit, ElementRef, HostListener, HostBinding} from "@angular/core";

@Directive({
    "selector":"[high-light-direc]"
})
export class HighlightDirec implements OnInit{
    @HostBinding('style') style:{backgroundColor:string};
    constructor(private elementRef:ElementRef){}
    ngOnInit(){
        
    }
    @HostListener('mouseenter') x(){
        this.style.backgroundColor = 'blue';
    }
    @HostListener('mouseleave') y(){
        this.style.backgroundColor='transparent';
    }
}

  <div>
    <p high-light-direc>
      {{toShow}}
    </p>
  </div>
&#13;
&#13;
&#13;

当我尝试为backgroundColor prop赋值时,我得到这个ERROR TypeError:无法设置属性&#39; backgroundColor&#39;未定义的。

所以如何将值赋给binded样式obj中的backgroundColor prop。

1 个答案:

答案 0 :(得分:0)

  

看看代码:

Stack Blitz

  

说明:

  1. 使用Style Sanitizer this.sanitizer.bypassSecurityTrustStyle
  2. 您必须发送已清理的CSS:@HostBinding('style') style: SafeStyle;
  3. 然后以这种方式设置值:

    @HostListener('mouseenter') x() {
       this.style = this.sanitizer.bypassSecurityTrustStyle("background-
       color: lime");
    }
    @HostListener('mouseleave') y() {
      this.style = this.sanitizer.bypassSecurityTrustStyle("background-color: transparent");
    }