Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 @HostBinding bind to style prop

Tags:

angular

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 .

like image 991
andrew s zachary Avatar asked Apr 02 '26 22:04

andrew s zachary


1 Answers

Take a look at the code:

Stack Blitz

Explanation:

  1. Use Style Sanitizer this.sanitizer.bypassSecurityTrustStyle
  2. You have to send sanitized CSS instead: @HostBinding('style') style: SafeStyle;
  3. 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");
    }
    
like image 188
Abhijit Kar ツ Avatar answered Apr 08 '26 06:04

Abhijit Kar ツ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!