Why doesn't this work, as stated in the docs ?
renderer.setElementClass(el, 'class1', false); // replace class
renderer.setElementClass(el, 'class2', true); // add a class
This results in the element only have the class2
instead of both.
Reference Angular2 renderer docs
The Renderer2 class is an abstraction provided by Angular in the form of a service that allows to manipulate elements of your app without having to touch the DOM directly.
This gives us direct access to the DOM, bypassing the Angular. There is nothing wrong with using it, but it is not advisable for the following reasons. Angular keeps the Component & the view in Sync using Templates, data binding & change detection, etc. All of them are bypassed when we update the DOM Directly.
Remember that Angular is a platform, and the browser is just one option for where we can render our app. So what you do is to give this responsibility to the Renderer class. First let’s create the ExploreRendererDirective.
The nativeElement Property contains the reference to the underlying DOM object. This gives us direct access to the DOM, bypassing the Angular. There is nothing wrong with using it, but it is not advisable for the following reasons.
Just to mention that Renderer is deprecated now, and have been replaced by Renderer2. In the Renderer2 class there are two methods that replace the setElementClass of the deprecated Renderer.
To add a class:
renderer.addClass(this.elementRef.nativeElement, 'popup');
To remove a class:
renderer.removeClass(this.elementRef.nativeElement, 'popup');
For more information see: https://angular.io/api/core/Renderer2
For code samples in form of tutorial see: https://alligator.io/angular/using-renderer2/ in particular the section of 'addClass / removeClass'
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