0

In an Angular application let's suppose we have a body element as

<body>
   ...
</body>

and now I want to set its background to some value using Angular Renderer2 as

this.renderer.setStyle(document.body, 'background', 'url("some-example-url");');

and nothing happens.

But now if I do it using setAttribute function as

this.renderer.setAttribute(document.body, 'style', 'background: url("some-example-url");');

this will work out fine.

My question is: can setStyle function operate on an element where the style attribute is not yet defined ?

Romuald
  • 205
  • 1
  • 13
  • After some further testing I ended up setting style attribute in my body element in the ngOnInit function as `ngOnInit() { this.renderer.setAttribute(document.body, 'style', ''); }` then set my style using setStyle as mentioned in the question above. Turns out it worked out fine. Now if anybody has a concise and clear answer about this function design I'll be glad to read it ! – Romuald Aug 06 '20 at 16:18

1 Answers1

0

Found out what the problem was in my code. Using setStyle with a semicolon-ended string as a value does not work.

// Bad
this.renderer.setStyle(document.body, 'background', 'url("some-example-url");');
// Good
this.renderer.setStyle(document.body, 'background', 'url("some-example-url")');

And after a deeper dive in Angular source code, especially in the platform-browser implementation of renderer it does not matter if a style attribute is set or not. Angular seems to handle it anyway.

Romuald
  • 205
  • 1
  • 13