Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 renderer setElementClass isAdd options does not work

Tags:

angular

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

like image 949
Romain Bruckert Avatar asked Mar 17 '17 12:03

Romain Bruckert


People also ask

What is renderer2 in Angular 2?

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.

Is it possible to bypass angular when updating the Dom?

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.

How do I render an app in angular?

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.

What is the use of nativeelement property in angular?

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.


1 Answers

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'

like image 113
tam.teixeira Avatar answered Oct 25 '22 17:10

tam.teixeira