angularangular-directiveangular-renderer2angular-renderer

Angular Renderer2 setStyle only if specific class present on host


I have a (spinner) directive that may add/remove a class (.spinner) using @HostBinding. It also adds/removes an img (spinner.gif) when activated.

If .spinner is present on the host, a bunch of styles defined in the scss file are applied:

.spinning {
  position: relative;
 }

.spinning img {
  display: block;
  width: 24px;
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%)
 }

I want to apply these styles on the host from within my directive. Is it possible to apply styles on the host only if a certain class is present using Renderer2 and ElementRef?

This obviously doesn't work:

this.renderer.setStyle(this.el.nativeElement, '.spinning position', 'relative');

Solution

  • Use can ElementRef to check whether the class present in the element or not

    ngOnInit(){
      let present = this.ele.nativeElement.classList.contains('open');
      if(present){
      //Then add your style
       this.renderer2.setStyle(this.el.nativeElement,'color','red');  
    
      }
      }
    

    Example:https://stackblitz.com/edit/angular-renderer2-dispatch-event-f4j56o