i am trying to bind to style prop of an ele with directive
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>
and when i try to assign a value to backgroundColor prop i get this ERROR TypeError: Cannot set property 'backgroundColor' of undefined .
so how to assign value to backgroundColor prop which is in Binded style obj .
Take a look at the code:
Stack Blitz
Explanation:
this.sanitizer.bypassSecurityTrustStyle@HostBinding('style') style: SafeStyle;Then set the values this way:
@HostListener('mouseenter') x() {
this.style = this.sanitizer.bypassSecurityTrustStyle("background-
color: lime");
}
@HostListener('mouseleave') y() {
this.style = this.sanitizer.bypassSecurityTrustStyle("background-color: transparent");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With