0

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');
Matt Saunders
  • 3,538
  • 2
  • 22
  • 30
kmansoor
  • 4,265
  • 9
  • 52
  • 95
  • could you provide the code in stackblitz.com for example? – Jecfish Aug 18 '18 at 15:26
  • I created a code sample with directive https://stackblitz.com/edit/so-spinner - refer to the `spinner directive` on adding and removing spinner class, refer to `app component` on how to use it. – Jecfish Aug 18 '18 at 15:40
  • @Chybie, thanks for your reply but I'm not asking how to add/remove a class. – kmansoor Aug 18 '18 at 15:42

1 Answers1

0

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

Chellappan வ
  • 23,645
  • 3
  • 29
  • 60