Arūnas Smaliukas Arūnas Smaliukas - 1 year ago 900
Javascript Question

Angular 2.x selecting DOM element

I know it should be easy but angular 2.0 has no many examples yet..

In one of my components in some case I need to add class on my body tag. But my application is bootstrapped deeper than body, so I need something like


but in Angular 2.0..

BTW, I know I can somehow bootstrap my application to include
tag, but I think in some other cases I would need to select some elements anyway, so I need a solution how to do this simple task - "select element and add class to it"

Answer Source


I'm not sure if DOM is actually still supported in RC. The related statements aren't very clear. Something like

DOM is only for internal use. Either access the DOM directly or use a custom renderer.

I haven't see how a custom renderer might be implemented or how to provide an implementation depending on the current platform (webworker, server, DOM thread).

Update This seems to be the Angular2 way

import { DOM } from 'angular2/src/platform/dom/dom_adapter';

DOM.addClass(DOM.query("body"), 'fixed');

Import from .../src/... at your own risk. .../src/... is considered private implementation and you can't expect any guarantees that the API won't change without notic.

I tried it in Dart and it works fine (not sure if the TS import above is correct though). In Dart DOM is exported by package:angular2/angular2.dart


If you want to access a DOM element that's outside of your Angular application root, just use document.querySelector(), no need to involve Angular.