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 ?
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.