What is the proper way to manipulate the DOM in Angular 2 RC?
For instance, I'm building a service for debug purposes to swap out .css file references in the document .
Prior to Angular 2 RC, it was possible to use BrowserDomAdapter
from DOM manipulations, like so:
import { BrowserDomAdapter } from 'angular2/platform/browser';
...
constructor(private domAdapter: BrowserDomAdapter) {
}
...
const document = this.domAdapter.defaultDoc();
This was inspired by the Title
service (now in @angular/platform-browser
). It seems that the Title
service still uses it internally, but it is no longer exported for use outside of Angular. I.e.
import { BrowserDomAdapter } from "@angular/platform-browser";
Results in:
Module '".../@angular/platform-browser/index"' has no exported member 'BrowserDomAdapter'
Steps:Use template reference and ViewChildren() to get HTML element. Inject Renderer and ElementRef into the constructor. Use the removeChild() method of the renderer to remove the child component. To get the host element, we need to use ElementRef.
Manipulating the DOM is easy with Angular. We can directly access the element by using ElementRef provided by @angular/core . If you manipulate it by using a directive (common use case) — most are likely to use nativeElement directly like this: It will correctly change the color of the element.
We use the ViewChild to get the ElementRef of an HTML element in the component class. Angular also inject ElementRef of the Host element of the component or directive when you request for it in the constructor.
import {BrowserDomAdapter} from '@angular/platform-browser/src/browser/browser_adapter';
UPDATE:(comment)
an issue on GitHub explains that the removal was indeed accidental, so hopefully it will be back in rc2. - @paul
For people like me, looking forward for interacting with the DOM in angular 2.4
:
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();
}
}
You should not use any adapter. This is implementation detail and should not be used. Instead @Inject(DOCUMENT)
into your component and use it.
Further reading: https://github.com/angular/angular/issues/8509
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With