6

How do I add more than just one class on the method Renderer2.addClass();

Example:

this.renderer.addClass(this.el.nativeElement, 'btn btn-primary')

When I try to do so I get the error:

ERROR DOMException: Failed to execute 'add' on 'DOMTokenList': The token provided ('btn btn-primary') contains HTML space characters, which are not valid in tokens.
    at EmulatedEncapsulationDomRenderer2.addClass
Felipe Bento
  • 83
  • 1
  • 2
  • 8
  • 1
    I guess you have to call it two times: `this.renderer.addClass(this.el.nativeElement, 'btn'); this.renderer.addClass(this.el.nativeElement, 'btn-primary');` – developer033 Feb 22 '20 at 21:36

3 Answers3

7

Unfortunately this.renderer.addClass() is accepting only one string without spaces.

What you can do is using the classList of native element to add multiple classes:

this.el.nativeElement.classList.add('btn', 'btn-primary');
Oussail
  • 2,200
  • 11
  • 24
  • Hi, @Oussail which of this 2 methods: ```renderer.addClass() / renderer.setAttribute(this.document, 'class', 'class-name'); or el.nativeElement.classList.add()``` is more efficient? – Robert Mar 25 '22 at 11:54
  • 1
    Hello @Robert sorry for the delay, whether using renderer.addClass() or ..classList.add() both are efficient depending on which environment you want to use them, if you are working only on web elements you may use .classList.add(), but if you are working on in non-DOM environments like native mobile, desktop and web worker rendering you may use renderer , I hope helped with this answer, (Correct me if I'm wrong, Thanks) – Oussail Apr 01 '22 at 12:11
  • Hi @Oussail, I found an article which says: "Renderer — Makes direct DOM access safe and it is Platform independent. It modifies the DOM elements without touch the DOM directly". What does it mean by "safe" and "It modifies the DOM elements without touch the DOM directly"? https://indepth.dev/posts/1336/how-to-do-dom-manipulation-properly-in-angular#definitions--2 – Robert Apr 02 '22 at 13:17
3

You can use this.renderer.setAttribute()

pseudo:

this.renderer.setAttribute(element, 'class', 'className1 className2 className3');

example:

renderer.setAttribute(cropBottomLine, 'class', 'crop-line crop-bottom-line');
2

Well, maybe the Renderer2 addClass() method doesn't support it, but this can be achieved just by using JavaScript :)

  const myClassess = 'col-12 col-sm-6 col-md-4';
  myClassess.split(' ').forEach((className: string) => {
      this.renderer2.addClass(this.el.nativeElement, className);
  });
WSD
  • 3,243
  • 26
  • 38