Difference between the two approaches in styling the host element dynamically in Angular

Viewed 430

According to the official document and other articles, Angular provides a couple of ways to style the host element.

via:

  • :host selector in .css file
  • @HostBinding
  • Renderer2

With the :host selector, I get to declare some static styles.

What about changing the style of the host element dynamically?
Say, I want to change the display state of the host element upon an event:

Using @HostBinding

export class UseHostBindingComponent {
  @HostBinding('style.display') display: string;

  // Change the display state of the host element
  onClick(): void {
    this.display = 'none';
  }
}

Using Renderer2

export class UseRenderer2Component {
  constructor(
    private renderer: Renderer2,
    private el: ElementRef
  ) {}

  // Change the display state of the host element
  onClick(): void {
    this.renderer.setStyle(this.el.nativeElement, 'display', 'none');
  }
}

Both approaches work but I just wonder the difference between them. Any insight would be appreciated!

1 Answers

With Renderer2 you manually update view, just in time when you need.

With HostBinding you tell Angular check binded property every time when Change Detection will be called and update View if value changed. So if Change Detection will be not called for your component, View will not update.

Related