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?
@HostBinding('class.open') isOpen: boolean = false;
@HostListener('click') toggleFunc(){
this.isOpen = !this.isOpen;
}
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With