More than one class on Renderer.addClass()
Asked Answered
I

4

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
Irkutsk answered 22/2, 2020 at 21:22 Comment(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');Pennywise
M
9

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');
Mustachio answered 22/2, 2020 at 21:46 Comment(3)
Hi, @Mustachio which of this 2 methods: renderer.addClass() / renderer.setAttribute(this.document, 'class', 'class-name'); or el.nativeElement.classList.add() is more efficient?Diatomite
Hello @Diatomite 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)Mustachio
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"? indepth.dev/posts/1336/…Diatomite
F
5

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');
Fem answered 17/2, 2022 at 7:8 Comment(0)
P
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);
  });
Protecting answered 8/2, 2021 at 23:35 Comment(0)
S
0

It's could be better how said @Vishnu Raghavan

example You can try:

this.renderer2.setAttribute(elemet, 'btn btn-primary')

This working wonderfull, I hope this can be help full.

Sorehead answered 25/2 at 0:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.