Romain Bruckert
Romain Bruckert

Reputation: 2610

Angular2 renderer setElementClass isAdd options does not work

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

Upvotes: 9

Views: 9746

Answers (3)

tam.teixeira
tam.teixeira

Reputation: 863

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://www.digitalocean.com/community/tutorials/angular-using-renderer2 in particular the section of 'addClass / removeClass'

Upvotes: 16

Sudha Priya
Sudha Priya

Reputation: 99

Renderer class has been removed in version 9 and migrated it to Renderer2

In Renderer -> setElementClass(renderElement, className, isAdd)

In Renderer2 -> isAdd ? addClass(renderElement, className) : removeClass(renderElement, className)

In short setElementClass method has been migrated into addClass method and removeClass method based on the third parameter passed in setElementClass.

  • If third parameter is true -> method will be addClass
  • If third parameter is false -> method will be removeClass

Upvotes: 2

Romain Bruckert
Romain Bruckert

Reputation: 2610

It turns out the isAdd option is the equivalent of a remove class, so the following works for toggling classes:

renderer.setElementClass(el, 'class1', false); // remove class1
renderer.setElementClass(el, 'class2', true); // add class2

Oh, nothing strange about calling a method setElementClass for removing it of course...

Upvotes: 12

Related Questions