0
votes

I'm learning angular and I am trying to set background color using _renderer.setElementStyle but its not apply can some one help me please

export class AppComponent {

  constructor(private elementRef: ElementRef,
    private render: Renderer) { }

  @HostListener("mouseover") onmouseover() {
    this.changeTextColor("red");
  }

    @HostListener("mouseleave") onmouseleave() {
    this.changeTextColor("blue");
  }

  changeTextColor(color: string) {
    this.render.setElementStyle(this.elementRef.nativeElement,"background-color",color);
  }
}

https://stackblitz.com/edit/angular-jsm9ii?file=src%2Fapp%2Fapp.component.ts

1
You can see something similar here stackoverflow.com/questions/39023277/… - Nguyen Phong Thien

1 Answers

1
votes

By default a component element has an inline display style. You should change this to a block style using the css:

:host {
  display: block;
}

this will make the stack work.

On the other hand, the Renderer is deprecated, and at the time of writing, one should use the Renderer2, which has the setStyle method

On the other other hand, using the Renderer for such a task should not be done. Mainly, you should never use renderer, unless you somehow cannot access the elements otherwise. For instance if they are injected through a 3rd party library.

I understand that you are trying out angular, but just to make it a full answer, best way to handle this is to use the @HostBinding() and either a style or class binding. This still does not take away the necessity of making it a block element. So perhaps it's better to attach bgColor to a block element inside the components template:

@HostBinding('style.backgroundColor')
bgColor: string = 'blue';

@HostListener("mouseover") onmouseover() {
  this.bgColor = "red";
}

@HostListener("mouseleave") onmouseleave() {
  this.bgColor = "blue";
}