Angular 2.x selecting DOM element Angular 2.x selecting DOM element angular angular

Angular 2.x selecting DOM element


Update

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

UpdateThis 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 notice.

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

Original

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.


As of Angular2 Version 2.0.0-beta.17.

Attribute Directives in Angular2 will do this for you nicely.

Please see this plunk written in TypeScript. This does what you want nicely.

The directive file my-highlight.ts has the line:

this.renderer.setElementClass(this.element, "red", true);

This sets the CSS class on the element.

While template.html has the actual element which is decorated with the directive [myHighlight]:

<p [myHighlight]>Mouseover to highlight me!</p>

This, to me, provides the least hack-ish answer to the question without any dependency on jqLite.


As of angular 2.4 you should inject the DOCUMENT and don't interact with any adapter:

import { Component, Inject } from '@angular/core';import { DOCUMENT } from '@angular/platform-browser';@Component({})export class MyClass {    constructor (@Inject(DOCUMENT) private document) { }    doSomething() {        this.document.someMethodOfDocument();    }}

Further reading: https://github.com/angular/angular/issues/8509