According to the official document and other articles, Angular provides a couple of ways to style the host element.
via:
:hostselector in.cssfile@HostBindingRenderer2
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!