More than one class on Renderer.addClass()

Viewed 4374

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
3 Answers

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');

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);
  });

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');
Related