BeetleJuice BeetleJuice - 2 months ago 37
TypeScript Question

Angular 2: change DOM elements outside the root AppComponent

I have an observable --

loading$
-- that outputs true when I want to show a loading overlay in the UI, and false when it's time to remove that overlay. The visibility is controlled with a CSS class.

When the Observable emits true, I want to add the CSS class to the
<body>
, and remove it on false.

html

<body class="">
<my-app>Angular app goes here</my-app>
</body>


As you can see, the
<body>
is outside of my
Angular 2
app, so I cannot use property binding to change the class. This is what I currently do:

AppComponent.ts

loading$.subscribe(loading =>{
if(loading) document.querySelector('body').classList.add('loading');
else document.querySelector('body').classList.remove('loading');
});


This works well. The
loading
class is added/removed when the
loading$
observable emits true/false. The problem is that I'd like to run my app in a web worker which means no access to the DOM. Plus, Angular recommends against manipulating the DOM directly.

How can I use
Angular
APIs to change
<body>
?

Angular 2
,
typescript 2
,
rxjs 5 beta 12


PS: This question looks promising, but the key link is dead. I've also seen a couple of suggestions that worked with Beta releases but are now obsolete (example)

Answer

Try to do like this:

<my-app>
  <div class="your-class-for-loading"></div>
</my-app>

When my-app is ready, div will be automatically removed.