gpt4 book ai didi

Angular 4 @HostBinding 绑定(bind)到 style 属性

转载 作者:行者123 更新时间:2023-12-02 10:56:21 26 4
gpt4 key购买 nike

我正在尝试使用指令绑定(bind)到 ele 的 style prop

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>

当我尝试为 backgroundColor 属性赋值时,我收到此错误 TypeError: Cannot set property 'backgroundColor' of undefined 。

那么如何为 Binded 样式 obj 中的 backgroundColor 属性赋值。

最佳答案

Take a look at the code:

Stack Blitz

Explanation:

  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");
    }

关于Angular 4 @HostBinding 绑定(bind)到 style 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49212855/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com