我试图用指令
绑定到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;
当我尝试为backgroundColor prop赋值时,我得到这个ERROR TypeError:无法设置属性&#39; backgroundColor&#39;未定义的。
所以如何将值赋给binded样式obj中的backgroundColor prop。
答案 0 :(得分:0)
看看代码:
说明:
this.sanitizer.bypassSecurityTrustStyle
@HostBinding('style') style: SafeStyle;
然后以这种方式设置值:
@HostListener('mouseenter') x() {
this.style = this.sanitizer.bypassSecurityTrustStyle("background-
color: lime");
}
@HostListener('mouseleave') y() {
this.style = this.sanitizer.bypassSecurityTrustStyle("background-color: transparent");
}