Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between @HostBinding() directive and ElementRef/Renderer?

I'm building a directive for a dropdown toggle. What I've seen is there are two approaches to build this directive. What should be the best practice?

Approach 1 - Using @HostBinding()

@HostBinding('class.open') isOpen: boolean = false;   
@HostListener('click') toggleFunc(){   
   this.isOpen = !this.isOpen;   
}   

Approach 2 - Using ElementRef and Renderer

    isOpen: boolean = false;
    constructor(private elementRef: ElementRef, private renderer: Renderer2){}

    @HostListener('click') onToggle(){
        this.isOpen = !this.isOpen;
        if(this.isOpen){
            this.renderer.addClass(this.elementRef.nativeElement, "open");
        }
        else{
            this.renderer.removeClass(this.elementRef.nativeElement, "open");    
        }

}   

Approach 1 look better as it is just 3 lines of code (hassle-free). But what should be the best practice? What should I use while creating such directives?
Does @HostBinding() and ElementRef/Renderer have different use cases?

like image 728
Siddharth Vinze Avatar asked Mar 09 '26 14:03

Siddharth Vinze


1 Answers

Its better to use the @HostBinding() approach because the code looks much cleaner than Renderer2 approach.

But if you want to bypass Angular's templating and make custom UI changes you should use Renderer2 approach and create your own custom renderer. https://angular.io/api/core/Renderer2#description

Just don't directly manipulate the DOM.

like image 118
the_mesh Avatar answered Mar 12 '26 06:03

the_mesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!